TabLayout提供了一个水平布局用于展示tabs,继承自HorizontalScrollView。一般与Viewpager结合使用实现页面和标签联动的效果,是时下APP中非常常用的一个控件
二:基本用法- xml中添加tab:
相当于给TabLayout添加了四个item,即
此时你的模拟器上的TabLayout拥有了四个指示标记。
2. 还可在代码中添加tabtableLayout = findViewById(R.id.tabLayout); tableLayout.addTab(tableLayout.newTab().setText("Tab0")); tableLayout.addTab(tableLayout.newTab().setText("Tab1")); tableLayout.addTab(tableLayout.newTab().setText("Tab2")); tableLayout.addTab(tableLayout.newTab().setText("Tab3")); tableLayout.addTab(tableLayout.newTab().setText("Tab4"));先获取TabLayout实例,然后通过调用方法添加Tab,Tab是TabLayout的内部类
三. 属性详解四,图文混排,Tab中添加图片
- 通过Tab.setCustomView(View view) 设置图片
- 自定义VIew布局
此布局名为tabview
- 代码设置:
//自定义方法用于VIew对象的创建,加载自己的布局 private View setCustomView(int drawable, String tabText) { View view = View.inflate(this, R.layout.tabview ,null); //动态加载布局 ImageView iv = (ImageView) view.findViewById(R.id.iv); TextView tv = (TextView) view.findViewById(R.id.tv); iv.setImageResource(drawable); tv.setText(tabText); return view; } new TabLayoutMediator(findViewById(R.id.tabLayout), viewPager2, new TabLayoutMediator.TabConfigurationStrategy() { @Override public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) { tab.setCustomView(setCustomView(R.drawable.ic_baseline_home_24,"item" + position)); //此处将自己的view对象加载给tab,使其显示出来 } }).attach();效果展示:



