Android design支持库中提供的TabLayout默认把Tab的OnClickListener给写死了,但是在项目中有时候需要做一些控制处理,
比如TabLayout和viewpager 绑定的情况下, Viewpager一开始不显示, 直到点击某个Tab才显示的情况下,
我们可以通过给TabLayout中的TabView重设OnClickListener解决这个问题
for (int i = 0; i < mTabLayout.getTabCount(); i++) { TabLayout.Tab tab = mTabLayout.getTabAt(i); if (tab != null) { tab.setCustomView(getTabView(i)); //对应tab定制view if (tab.getCustomView() != null) { View tabView = (View) tab.getCustomView().getParent(); //获得tab对应父item tabView.setTag(i); // 父item放入标记值 tabView.setOnClickListener(mTabOnClickListener); //设置点击事件 } }
}
//自定义的TabView,布局和图标换成你想要的即可
app:tabBackground="@drawable/tab_bg_selector"
public View getTabView(int position) {
//获得viewView v = LayoutInflater. from(ParentEditorActivity. this).inflate(R.layout. go, null);
ImageView img = (ImageView) v.findViewById(R.id.icon_item); img.setImageResource(imageViewRes[position]); return v; }
private View.OnClickListener mTabOnClickListener = new View.OnClickListener() { @Override public void onClick(View view) { int pos = (int) view.getTag(); Log.d(TAG, "onClick: mviewpager?" + mViewpager.getVisibility()); if (mViewpager.getVisibility() == View.INVISIBLE) { mViewpager.setVisibility(VISIBLE); AnimUtils.stickerExitAnim(mViewpager, mTabLayout, false, getClickAnimListener(false)); } TabLayout.Tab tab = mTabLayout.getTabAt(pos); if (tab != null) { tab.select(); } } };
app:tabBackground="@drawable/tab_bg_selector"
设置整个tab的背景色
//getTabView所需要的渲染文件,自定义即可
xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:id="@+id/ll_item" android:background="@drawable/tab_bg_selector" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/icon_item" android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/ic_launcher"/> LinearLayout>
//background的select文件(在这个Demo里面需要,可以不写)
xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android" android:exitFadeDuration="@android:integer/config_shortAnimTime"> <item android:drawable="@color/cpb_green" android:state_selected="true"/> //选中状态 <item android:drawable="@color/cpb_green" android:state_pressed="true"/> //按下状态 <item android:drawable="@drawable/md_transparent"/> //平时状态 selector>