修改tablayout中圖片和文字的間距

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容