如何在自定义TabLayout中更改选定文本的颜色

7
我有一个包含4个选项卡的ViewPager,使用TabLayout实现。因为我想要更改字体为自定义字体,所以我使用了自定义的TabLayout。现在问题是选中的选项卡文本颜色不会随着tabSelectedTextColor的更改而改变。
这是我的Java代码:
package com.example.noavaran.drugstore.Activity;

import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatTextView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.noavaran.drugstore.Fragment.AddressFragment;
import com.example.noavaran.drugstore.Fragment.IssueFragment;
import com.example.noavaran.drugstore.Fragment.MenuFragment;
import com.example.noavaran.drugstore.Fragment.SearchFragment;
import com.example.noavaran.drugstore.Helper.CustomViewPager;
import com.example.noavaran.drugstore.R;

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

import layout.fragment_approve;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
import uk.co.chrisjenx.calligraphy.CalligraphyUtils;

public class MainPageActivity extends AppCompatActivity {
    private TabLayout tabLayout;
    public Context context;
    public Typeface tf;
    public static boolean a=false;
    private CustomViewPager viewPager;
    private int[] tabIcons = {
            R.drawable.menu,
            R.drawable.address_icon,
            R.drawable.search_icon,
            R.drawable.issue_icon
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_page);
         tf = Typeface.createFromAsset(getAssets(), "IRANSans_Bold.ttf");

        tabCustomization();
        /*changeTabsFont();*/
        setupTabIcons();
    }

    private void tabCustomization() {
        viewPager = (CustomViewPager) findViewById(R.id.viewPager);
        viewPager.setPagingEnabled(false);

        setupViewPager(viewPager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);

        tabLayout.setupWithViewPager(viewPager);
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());


        adapter.addFragment(new MenuFragment(), "menu");

        adapter.addFragment(new AddressFragment(), "Address");
        adapter.addFragment(new SearchFragment(), "Searcg");
        adapter.addFragment(new IssueFragment(), "Issue");

        viewPager.setAdapter(adapter);
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);

            tab.setCustomView(adapter.getTabView(tabLayout,i));
        }


        ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
        int tabsCount = vg.getChildCount();
        Log.i("TabChild",String.valueOf(tabsCount));


// Iterate over all tabs and set the custom view

    }
    public void setupViewPager(ViewPager viewPager) {

    }
    private void setupTabIcons() {

        tabLayout.getTabAt(0).setIcon(tabIcons[0]);
        tabLayout.getTabAt(1).setIcon(tabIcons[1]);
        tabLayout.getTabAt(2).setIcon(tabIcons[2]);
        tabLayout.getTabAt(3).setIcon(tabIcons[3]);


        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){


            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                tab.getIcon().setColorFilter(Color.parseColor("#a8a8a8"), PorterDuff.Mode.SRC_IN);


            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                tab.getIcon().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
            }

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

            }
        });
    }


    class ViewPagerAdapter extends FragmentPagerAdapter {

        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }


        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }
        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }
        public View getTabView(TabLayout tabLayout,int position) {
            // Given you have a custom layout in `res/layout/custom_tab.xml` with a TextView and ImageView

            View view = LayoutInflater.from(getApplicationContext())
                    .inflate(R.layout.custom_tab, tabLayout, false);
            TextView textView= (TextView) view.findViewById(R.id.tabText);

            textView.setText(getPageTitle(position));
            textView.setTypeface(tf);

            ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
            imageView .setImageResource(tabIcons[position]);

            return view;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }

    }

    //Caligraphy Library
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }
}

我的自定义布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="5px"
        android:id="@+id/imageView" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="New Text"
        android:textColor="@android:color/white"
        android:gravity="center"

        android:id="@+id/tabText" />
</LinearLayout>

这是我的tablayout标签:
   <android.support.design.widget.TabLayout
        android:layout_weight="4"
        android:id="@+id/tabs"
        android:layout_gravity="right"
        app:tabGravity="fill"
        fontPath="@string/fontsIran"
        app:tabTextAppearance="@drawable/selected_text"
        android:layoutDirection="rtl"
        app:tabBackground="@drawable/tabformat"
        app:tabTextColor="@android:color/white"
        app:tabSelectedTextColor="@color/color_tab_gray"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/color_main"
        />

我只是根据javacoder在这篇评论中所说的做了以下操作,但我不知道为什么在选择另一个选项卡后之前的文本会被删除。
@Override
            public void onTabSelected(TabLayout.Tab tab) {
                tab.getIcon().setColorFilter(Color.parseColor("#a8a8a8"), PorterDuff.Mode.SRC_IN);
                TextView txt=(TextView)findViewById(R.id.tabText);
                txt.setTextColor(Color.GRAY);
                tab.setCustomView(txt);

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                tab.getIcon().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
                TextView txt=(TextView)findViewById(R.id.tabText);
                txt.setTextColor(Color.YELLOW);
                tab.setCustomView(txt);
            }

你尝试过这个答案吗?https://dev59.com/CV0Z5IYBdhLWcg3w3Dfk#31019421 - Muhammad Waleed
@Javacoder 我尝试在onTabSelected事件中使用tab.getCustomView()来实现,但是没有任何方法或属性可以这样做。 - Hussein Ojaghi
@Javacoder 如何使用tab.SetCustomView实现这个功能。 - Hussein Ojaghi
你解决了这个问题吗? - Nabeel K
@NabeelK 是的,我使用了一个自定义适配器,它扩展了 ViewPagerAdapter 并且很好地修复了问题。 - Hussein Ojaghi
请问您能否发布解决方案? - Nabeel K
2个回答

7

以下是我用于更改选中时的选项卡布局的方法。

这是您的适配器:

 class ViewPagerAdapter extends FragmentPagerAdapter {
   ...
   // I add two func here.
   public void SetOnSelectView(TabLayout tabLayout,int position)
   {
    TabLayout.Tab tab = tabLayout.getTabAt(position);
    View selected = tab.getCustomView();
    TextView iv_text = (TextView) selected.findViewById(R.id.tabText);
    iv_text.setTextColor(mContext.getResources().getColor(R.color.white));
   }

   public void SetUnSelectView(TabLayout tabLayout,int position)
   {
    TabLayout.Tab tab = tabLayout.getTabAt(position);
    View selected = tab.getCustomView();
    TextView iv_text = (TextView) selected.findViewById(R.id.tabText);
    iv_text.setTextColor(mContext.getResources().getColor(R.color.textblack));
   }
   ...
 }

在活动中

 //Add this
 tabLayout.addOnTabSelectedListener(OnTabSelectedListener);

这里是OnTabSelectedListener

 private TabLayout.OnTabSelectedListener OnTabSelectedListener = new TabLayout.OnTabSelectedListener(){
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        int c = tab.getPosition();
        yourAdapter.SetOnSelectView(tabLayout,c);
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
        int c = tab.getPosition();
        yourAdapter.SetUnSelectView(tabLayout,c);
    }

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

    }
};

1
这段代码能运行但有一个小 bug。在 onCreate() 函数中增加 yourAdapter.SetOnSelectView(tabLayout,0); 以修复它。谢谢。 - Nabeel K
完美的解答,以查找选项卡自定义视图并更改其颜色,我在与ViewPager和选项卡相关联的主活动中使用了此代码,而不是在适配器中,并且它也很好地工作 :) - Ramkesh Yadav
你只需要一个选择器就可以了!!! - Ehsan

-3
<android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        app:tabGravity="fill"
        android:layout_gravity="bottom"
        android:background="@android:color/background_dark"
        app:tabTextColor="@color/text_tab_unselected"
        app:tabSelectedTextColor="@color/text_tab_selected"
        app:tabTextAppearance="@style/TextAppearance.Widget.TabWidget"/>

样式

<style name="TextAppearance.Widget.TabWidget" parent="android:TextAppearance.Medium">
        <item name="android:textColor">@drawable/tab_text_color</item>
        <item name="android:textSize">10dp</item>
    </style>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接