修改tablayout中图片和文字的间距

1、设置图片的选择器

图片替换成自己的就行

<?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、重写一个图标+文字的布局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文件里添加如下函数:

    // 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;
    }

然后进行调用:

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控件的高度调小
最后tablayout和viewpager对应的监听事件

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容