使用 TabLayout 时如何更改选项卡背景颜色? [英] How do I change a tab background color when using TabLayout?

查看:54
本文介绍了使用 TabLayout 时如何更改选项卡背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在主要活动中的代码

This is my code in the main activity

public class FilterActivity extends AppCompatActivity {

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

    // Get the ViewPager and set it's PagerAdapter so that it can display items
    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    PageAdapter pageAdapter = new PageAdapter(getSupportFragmentManager(), FilterActivity.this);
    viewPager.setAdapter(pageAdapter);

    // Give the TabLayout the ViewPager
    final TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
    tabLayout.setupWithViewPager(viewPager);



  }
}

这是我在 XML 中的代码

And this is my code in the XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

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

    <android.support.design.widget.TabLayout
        android:id="@+id/sliding_tabs"
        android:layout_width="fill_parent"
        style="@style/MyCustomTabLayout"
        android:layout_height="48dp"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1"
        android:background="@android:color/white" />

</LinearLayout>

我想改变一个标签被选中时的背景颜色

I want to change the background color of one tab when it's selected

推荐答案

最终对我有用的方法与@如果我是DJ 建议的类似,但是tabBackground 应该在 中layout 文件和 notstyle 内,所以它看起来像:

What finally worked for me is similar to what @如果我是DJ suggested, but the tabBackground should be in the layout file and not inside the style, so it looks like:

res/layout/somefile.xml:

<android.support.design.widget.TabLayout
    ....
    app:tabBackground="@drawable/tab_color_selector"
    ...
    />

和选择器res/drawable/tab_color_selector.xml:

and the selector res/drawable/tab_color_selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/tab_background_selected" android:state_selected="true"/>
    <item android:drawable="@color/tab_background_unselected"/>
</selector>

这篇关于使用 TabLayout 时如何更改选项卡背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆