1、設(shè)置圖片的選擇器
圖片替換成自己的就行
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@mipmap/home_highlight"/>
<item android:state_selected="false" android:drawable="@mipmap/home_unselected"/>
</selector>
2点弯、xml
布局中放tablayout和viewpager就行
3忌卤、重寫一個(gè)圖標(biāo)+文字的布局tab_item_view.xml妖异,大致如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textview"
android:textSize="11dp"
android:textColor="@color/c_999999"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Activity
在activity的Java文件里添加如下函數(shù):
// Tab自定義view
public View getTabView(String title, int image_src) {
View v = LayoutInflater.from(getApplicationContext()).inflate(R.layout.tab_item_view, null);
TextView textView = (TextView) v.findViewById(R.id.textview);
textView.setText(title);
ImageView imageView = (ImageView) v.findViewById(R.id.imageview);
imageView.setImageResource(image_src);
return v;
}
然后進(jìn)行調(diào)用:
tabLayout = (TabLayout) findViewById(R.id.tab);
tablayout.addTab(tablayout.newTab().setText(R.string.home).setIcon(R.drawable.selector_home));
tablayout.addTab(tablayout.newTab().setText(R.string.withm).setIcon(R.drawable.selector_banmi));
tablayout.getTabAt(0).setCustomView(getTabView(getResources().getString(R.string.home),R.drawable.selector_home));
tablayout.getTabAt(1).setCustomView(getTabView(getResources().getString(R.string.withm),R.drawable.selector_banmi));
可以在布局文件里將TabLayout控件的高度調(diào)小
最后tablayout和viewpager對(duì)應(yīng)的監(jiān)聽事件
tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewpager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewpager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tablayout));
如果圖片不用選擇器的話用下面的
https://blog.csdn.net/weixin_34384681/article/details/87001968