您的位置:首页 > 其它

TabLayout实现每个tab有一个不同的图片,选中改变图片

2016-09-23 19:48 471 查看
自定义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);
}

a0eb
@Override
public void onTabReselected(TabLayout.Tab tab) {

}
});


如图:





想要实现如上的方法,很简单:

搞定。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐