当使用TabLayout时,我如何更改选项卡的背景颜色?

144

这是我在主活动中的代码

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代码

<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>

当选中一个选项卡时,我想要改变它的背景颜色。

14个回答

0

您可以在以下方式中使用 tab.view.setBackground(drawable)

tabLayout.addOnTabSelectedListener

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            tab.view.setBackground(getResources().getDrawable(R.drawable.ic_rectangle_1345));
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            tab.view.setBackgroundColor(Color.TRANSPARENT);
        }

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

        }
    });

0

您可以通过此属性更改选项卡的背景颜色。

<android.support.design.widget.TabLayout
android:id="@+id/tabs"
style="@style/CategoryTab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
'android:background="@color/primary_color"/>'

0
另一种解决顽固情况的方法是将TabLayout的背景设置为形状选择器,就像这个例子中所示:
在/res/drawable目录下的tablayout_bg.xml文件中。
 <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@color/white" />
</shape>

fragment_layout.xml

<com.google.android.material.tabs.TabLayout
 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/tablayout_bg"
        app:tabMode="scrollable"
        >

-3

最简单的解决方案之一是从colors.xml文件中更改colorPrimary。


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