1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <?xml version="1.0" encoding="utf-8"?>布局 <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> //代码 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | package zhanghaijiao.bawei.com.tablayout_demo;
import android.support.design.widget.TabLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TabLayout myTab=findViewById(R.id.mytab);
//添加选项卡 myTab.addTab(myTab.newTab().setText("新闻")); myTab.addTab(myTab.newTab().setText("社会")); myTab.addTab(myTab.newTab().setText("社会1")); myTab.addTab(myTab.newTab().setText("社会2")); myTab.addTab(myTab.newTab().setText("社会3")); myTab.addTab(myTab.newTab().setText("社会4"));
//选项卡被选中的监听事件 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) {
} });
} } |