1、 添加design包
在main_activity.xml中添加如下代碼 :
< LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
tools:context="com.usher.studytablayout.MainActivity">
<android.support.design.widget.TabLayout
android:id="@+id/main_tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#D2A2CC" /></LinearLayout>
2、編寫MainActivity代碼
public class MainActivity extends AppCompatActivity {
private TabLayout tablayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tablayout = (TabLayout) findViewById(R.id.main_tablayout);
tablayout.addTab(tablayout.newTab().setText("新聞"));
tablayout.addTab(tablayout.newTab().setText("天氣"));
tablayout.addTab(tablayout.newTab().setText("娛樂"));
}
}
這個(gè)東西就是TabLayout的基本顯示,然后它有一些屬性如下:
- tabIndicatorColor 下方滾動(dòng)的下劃線顏色
- tabTextColor 默認(rèn)的文字顏色
- tabSelectedTextColor 被選中后文字的顏色
- tabIndicatorHeight 下劃線的高度
- app:tabMode="scrollable" 很多標(biāo)題的時(shí)候可以左右滑動(dòng)
然后關(guān)于TabLayout的顯示你還可以給他加上圖片,代碼如下:
public class MainActivity extends AppCompatActivity {
private TabLayout tablayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tablayout = (TabLayout) findViewById(R.id.main_tablayout);
tablayout.addTab(tablayout.newTab().setText("新聞").setIcon(R.mipmap.icon1));
tablayout.addTab(tablayout.newTab().setText("天氣").setIcon(R.mipmap.icon2));
tablayout.addTab(tablayout.newTab().setText("娛樂").setIcon(R.mipmap.icon3 ));
}