如何在使用TabLayout时更改选项卡背景颜色?

这是我主要活动中的代码

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> 

我想在选中时更改一个选项卡的背景颜色

最后为我工作的是什么@如果我是DJbuild议,但tabBackground应该在layout文件中,而不是style ,所以它看起来像:

res/layout/somefile.xml

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

和select器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> 

你可以试试这个:

 <style name="MyCustomTabLayout" parent="Widget.Design.TabLayout"> <item name="tabBackground">@drawable/background</item> </style> 

在你的后台xml文件中:

 <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_selected="true" android:drawable="@color/white" /> <item android:drawable="@color/black" /> </selector> 

在xml中添加属性:

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

并在可绘制文件夹tab_color_selector.xml中创build

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

你有没有试过检查API ?

您将需要为OnTabSelectedListener事件创build一个侦听器,然后当用户select任何选项卡时,您应该检查它是否是正确的,然后使用tabLayout.setBackgroundColor(int color)更改背景色,或者如果不正确选项卡确保使用相同的方法再次变回正常的颜色。