Как установить разные цвета текста и фона на TabLayout? - PullRequest
0 голосов
/ 30 января 2019

На ThemeActivity моего приложения цвет панелей инструментов зависит от предмета, он может быть коричневым, красным или розовым.Я хотел бы изменить цвета текста и фона текущей выбранной вкладки на вкладке вкладок, чтобы она могла совпадать с цветом панели инструментов, а также изменить цвета текста и фона других вкладок (чтобы они имелибелый фон с темным текстом).

Я слежу за этим ответом , что хорошо, но так как TabLayout определяется его стилем на style.xml, я не вижукак я могу изменить стиль каждый раз, когда меняется тег и цвет текста.

Что у меня сейчас:

enter image description here (для всех цветов)

Что я хочу:

enter image description here enter image description here

Класс ThemeActivity:

public class ThemeActivity extends AppCompatActivity {

    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private Toolbar mToolbar;

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

        initializeFields();
    }

    private void initializeFields() {
        String theme = getIntent().getStringExtra("Theme");

        mToolbar = findViewById(R.id.themeToolbar);
        setSupportActionBar(mToolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle(theme);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowCustomEnabled(true);
        setToolbarColor(theme);

        mTabLayout = findViewById(R.id.themeTabLayout);
        mViewPager = findViewById(R.id.themeViewPager);
        PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), ThemeActivity.this);
        mViewPager.setAdapter(pagerAdapter);
        mTabLayout.setupWithViewPager(mViewPager);

        for (int i = 0; i < mTabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = mTabLayout.getTabAt(i);
            tab.setCustomView(pagerAdapter.getTabView(i));
        }
    }

    private void setToolbarColor(String theme) {
        if (theme.equals("Feminismo")) {
            mToolbar.setBackgroundColor(getResources().getColor(R.color.flatFeminism));
        } else if (theme.equals("Racismo")) {
            mToolbar.setBackgroundColor(getResources().getColor(R.color.flatRacism));
        } else {
            mToolbar.setBackgroundColor(getResources().getColor(R.color.flatLgbt));
        }
    }

    class PagerAdapter extends FragmentPagerAdapter {

        String tabTitles[] = new String[]{"Sobre", "Comunidades", "Artigos"};
        Context context;

        public PagerAdapter(FragmentManager fm, Context context) {
            super(fm);
            this.context = context;
        }

        @Override
        public Fragment getItem(int i) {
            switch (i) {
                case 0:
                    return new AboutFragment();
                case 1:
                    return new CommunityFragment();
                case 2:
                    return new ArticlesFragment();
                default:
                    return null;
            }
        }

        @Override
        public int getCount() {
            return tabTitles.length;
        }

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

        public View getTabView(int position) {
            View tab = LayoutInflater.from(ThemeActivity.this).inflate(R.layout.custom_tab, null);
            TextView tv = tab.findViewById(R.id.custom_text);
            tv.setText(tabTitles[position]);
            return tab;
        }

    }
}

Часть в style.xml TabLayout

<style name="Base.Widget.Design.TabLayout" parent="android:Widget">
        <item name="tabBackground">@drawable/tab_background</item>
        <item name="tabIndicatorColor">#ff00ff</item>
        <item name="tabIndicatorHeight">2dp</item>
</style>

Activity_theme.xml (довольно стандартный вид)

<RelativeLayout 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"
    tools:context=".ThemeActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/themeBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <include
            android:id="@+id/themeToolbar"
            layout="@layout/main_toolbar"></include>

        <android.support.design.widget.TabLayout
            android:id="@+id/themeTabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/themeToolbar">
    </android.support.design.widget.TabLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/themeViewPager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/themeBarLayout"></android.support.v4.view.ViewPager>

</RelativeLayout>

Остальное - то же, что ответил Дэниел Ньюджент.(tab_background.xml, tab_background_selected.xml, tab_background_unselected.xml, только невыбранный цвет, который я изменил на #ffffff)

1 Ответ

0 голосов
/ 30 января 2019

Вам просто нужно получить свой tabLayout и установить его так:

tablayout.setTabTextColors(Color.parseColor("#7DC1C6"), resources.getColor(R.color.white))

Первый цвет нормальный, а второй выбранный.

А для фона вы можете использоватьtabLayout.background.

...