需要添加依赖,添加后会报错,改为26.+就行
xml布局代码
<
RelativeLayout
xmlns:android
=
"http://schemas.android.com/apk/res/android"
xmlns:app
=
"http://schemas.android.com/apk/res-auto"
xmlns:tools
=
"http://schemas.android.com/tools"
android:layout_width
=
"match_parent"
android:layout_height
=
"match_parent"
tools:context
=
"zhanghaijiao.bawei.com.tablayout_demo.MainActivity"
>
<!--
app:tabGravity="center" 设置居中对齐
app:tabIndicatorColor="@color/colorAccent" 下滑线的颜色
app:tabMode="scrollable" 设置tabLayoout菜单的模式,,,scrollable可以横向滚动 fixed:固定
app:tabSelectedTextColor="@color/colorPrimaryDark" 选中的时候文字的颜色
app:tabTextColor="@color/colorPrimary" 文本默认的颜色
-->
<
android.support.design.widget.TabLayout
android:layout_width
=
"match_parent"
android:layout_height
=
"50dp"
android:id
=
"@+id/mytab"
app:tabGravity
=
"center"
app:tabIndicatorColor
=
"@color/colorAccent"
app:tabMode
=
"scrollable"
app:tabSelectedTextColor
=
"@color/colorPrimaryDark"
app:tabTextColor
=
"@color/colorPrimary"
></
android.support.design.widget.TabLayout
>
</
RelativeLayout
>
只添加选项卡
myTab.addTab(myTab.newTab().setText(
"新闻"
));
监听事件
//选项卡被选中的监听事件
myTab.setOnTabSelectedListener(
new
TabLayout.OnTabSelectedListener() {
@Override
public
void
onTabSelected(TabLayout.Tab tab) {
Toast.makeText(MainActivity.
this
,tab.getText().toString(),Toast.LENGTH_SHORT).show();
}
@Override
public
void
onTabUnselected(TabLayout.Tab tab) {
}
@Override
public
void
onTabReselected(TabLayout.Tab tab) {
}
});
public
class
Fragment_04