安卓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]

如果有什麼問題,歡迎大家指導。並相互聯繫,希望能夠通過文章互相學習。

											                               	---財財親筆
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章