安卓Tablayout自定义文字、指示器长度和颜色

废话不多说,先上效果图。没有效果图的文章都是扯淡:

在这里插入图片描述

安卓Tablayout自定义文字、指示器长度和颜色

之前写过一篇博客是tablayout+viewpager的基本实现,类似今日头条的界面。随着需求和UI的不断提升,Android端需要自定义的功能越来越多,tablayout的使用越来越频繁,自定义指示器和自定义tab字体的需求就越来越多,自己做的时候也找了好多资料去参考,但基本上都达不到我的需求,所以还是自食其力、自力更生吧。借此记录一下,也希望能够帮助到你。

新的改变

1.自定义tab可以实现呢字体加粗,字体大小设置等;
2.自定义指示器支持各式各样的图片或文字;

OK 贴代码吧:

先来xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        app:tabGravity="center"
        app:tabMode="scrollable"
        app:tabIndicatorFullWidth="false"
        app:tabIndicatorColor="@color/tra"
        app:tabBackground="@color/tra"
        app:tabRippleColor="@color/tra"
        app:tabTextColor="#000000"
        app:tabSelectedTextColor="#38A9FF"/>
    
    <androidx.viewpager.widget.ViewPager
        android:id="@+id/vierpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

activity.class

package com.edu.demo8;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    String[] title = {"热门","外语","舞蹈","音乐","篮球","主播","游泳","电竞","首富"};

    List<Fragment> fragments = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TabLayout tableLayout = findViewById(R.id.tablayout);
        ViewPager viewPager = findViewById(R.id.vierpager);

        //设置tablayout+viewpager
        for (int i = 0; i < title.length; i++){
            fragments.add(ItemFragment.newInstance(title[i]));
        }
        //加适配器
        viewPager.setAdapter(adapter);
        //绑定联动
        tableLayout.setupWithViewPager(viewPager);

        //设置自定义tab
        for (int i = 0; i < tableLayout.getTabCount(); i++){
            TabLayout.Tab tab = tableLayout.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(getTabView(i));
            }
        }
        //监听滑动
        tableLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if(tab!= null){
                    changeTabTextView(tab, true);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if(tab!= null){
                    changeTabTextView(tab, false);
                }
            }

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

            }
        });

        //默认选中第一个
        changeTabTextView(tableLayout.getTabAt(0), true);

    }

    /**
     * 修改选中时的状态
     * @param tab
     * @param b
     */
    private void changeTabTextView(TabLayout.Tab tab, boolean b) {
        TextView tablayout_item_txt = tab.getCustomView().findViewById(R.id.tablayout_item_txt);
        TextView tablayout_item_ind = tab.getCustomView().findViewById(R.id.tablayout_item_ind);
        if(b){
            tablayout_item_ind.setBackgroundColor(Color.parseColor("#39AAFE"));
            tablayout_item_txt.getPaint().setFakeBoldText(true);
            tablayout_item_txt.setTextColor(Color.parseColor("#39AAFE"));
        }else{
            tablayout_item_ind.setBackgroundColor(Color.parseColor("#00000000"));
            tablayout_item_txt.getPaint().setFakeBoldText(false);
            tablayout_item_txt.setTextColor(Color.parseColor("#000000"));
        }
    }

    //获取每一个tab的view
    public View getTabView(int position) {
        View view = LayoutInflater.from(this).inflate(R.layout.tablayout_item, null);
        TextView textView = view.findViewById(R.id.tablayout_item_txt);
        textView.setText(title[position]);
        return view;
    }


    /**
     * 添加fragment的适配器
     */
    FragmentPagerAdapter adapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
        @NonNull
        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return title[position];
        }
    };

}

item的xml:

<?xml version="1.0" encoding="utf-8"?>

<TextView
    android:id="@+id/tablayout_item_txt"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:text="自定义"
    android:background="?selectableItemBackgroundBorderless"
    android:gravity="center"
    android:textColor="#000000"
    android:textSize="14dp" />

<TextView
    android:id="@+id/tablayout_item_ind"
    android:layout_width="10dp"
    android:layout_height="5dp"
    android:layout_marginTop="1dp"
    android:background="#00000000"/>

ItemFragment:

package com.edu.demo8;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class ItemFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view4 = inflater.inflate(R.layout.sele_fragment_item4, container, false);
        return view4;
    }

    public static Fragment newInstance(String i) {
        ItemFragment fragment = new ItemFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("TABLAYOUT_FRAGMENT", i);
        fragment.setArguments(bundle);
        return fragment;
    }
}

sele_fragment_item4.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:textSize="30dp"
    android:textColor="#000000"
    android:text="123321">

</TextView>

我的思路是在设置每一个tab的时候去添加一个自定义的指示器。随着tab的状态的改变去显现自定义的指示器就好,可以解决我的需求。

以上就是所有的代码

附上demo源码。

源码:源码请点这里


q:486789970
email:[email protected]

如果有什么问题,欢迎大家指导。并相互联系,希望能够通过文章互相学习。

											                               	---财财亲笔

猜你喜欢

转载自blog.csdn.net/qq_35840038/article/details/107001231