colors - 以编程方式更改 ColorDrawable 选定状态颜色/ Tablayout 背景颜色
问题描述
我有一个 tab_color_selector.xml 可绘制对象,我在 TabLayout 中使用它。
我想在 onTabSelected 上更改它的选定状态颜色。
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/medicine_green"
android:state_selected="true" />
<item android:drawable="@color/base_gray" />
</selector>
表格布局 xml:
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/c_white"
app:tabBackground="@drawable/tab_color_selector"
app:tabIndicatorColor="@color/summary_blue"
app:tabIndicatorHeight="5px"
app:tabMode="fixed"
app:tabSelectedTextColor="@color/c_white"
app:tabTextAppearance="@android:style/TextAppearance.Widget.TabWidget"
app:tabTextColor="@color/c_white" />
在这里,我想以编程方式更改 ColorDrawable android:state_selected="true" 颜色。
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
((ColorDrawable)tabLayout.getBackground()).setColor(getResources().getColor(R.color.material_yellow400));
tabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.color_17));
break;
case 1:
((ColorDrawable)tabLayout.getBackground()).setColor(getResources().getColor(R.color.material_pink400));
tabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.out_pat_green));
break;
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
我尝试了 setColor() 和 setColorFilter() 以及 setBackground()
解决方案
创建样式并将其作为标签添加到 TabLayout 小部件中
推荐阅读
- html - 标题中包含多行的粘性标题表
- c - 使用 strcmp/strncmp 比较 int8_t 和 char*
- java - 通过多个属性对对象内的列表进行分组:Java 8
- sql-server - 使用 Linked Server TO Oracle 进行插入、更新、删除
- automata - 构造确定性有限自动机等于非确定性自动机
- apache - Apache2:.htaccess 重定向太多
- django - Virtualenv已激活但python仍在运行系统版本
- mysql - mysql坏查询性能不一致
- javascript - 每个条目带有背景颜色填充和边框的 Css Textarea 文本
- angular - 在 Linux 上更新 protoc-gen-grpc-web