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

自定义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) {

            }
        });

如图:
点击

不点

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

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值