自定義tab,背景選擇器
如下:
1、每個tab裏面的圖片的佈局,使用textview,注意不能用button,也不能設置textview的clickable=”true”,否則tablayout就不能選擇了
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="@+id/main_tv"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
主界面:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="@+id/main_tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/orange"/>
</LinearLayout>
背景選擇器,我這有四個tab,每個的圖片都不相同,但是格式相同,所以這裏列出一個:
<?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/ic_home_home_focus"/>
<item android:state_selected="false" android:drawable="@mipmap/ic_home_home_normal"/>
</selector>
最後主界面代碼:
//加載自定義的佈局
for (int i = 0; i < 4; i++) {
TabLayout.Tab tab=mainTablayout.newTab();
View view= LayoutInflater.from(this).inflate(R.layout.main_top_layout,null);
TextView tv= (TextView) view.findViewById(R.id.main_tv);
tv.setBackgroundResource(bgs[i]);
tab.setCustomView(view);
if (i==0)
tv.setFocusable(true);
mainTablayout.addTab(tab);
}
監聽事件,tab選中改變的時候,改變圖片:
mainTablayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
tab.getCustomView().findViewById(R.id.main_tv).setFocusable(true);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
tab.getCustomView().findViewById(R.id.main_tv).setFocusable(false);
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
如圖:
想要實現如上的方法,很簡單:
搞定。