【发布时间】:2017-10-21 19:17:28
【问题描述】:
我正在尝试创建自定义选项卡布局,因为我需要在 TextView 旁边设置徽章计数器。我已将 id 设置为@android:id/text1,正如文档中提到的那样。
当我的自定义选项卡被选中时,TextView 颜色不会自动更改。如何以正确和干净的方式实现它?
正确选择默认选项卡:
错误选择的自定义选项卡(文本为灰色但应为白色):
代码
PagerAdapter adapter = new MyAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
TabLayout.Tab tab = tabLayout.getTabAt(2);
if (tab != null) {
tab.setCustomView(R.layout.tab_proposed_rewards);
}
布局
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="@android:id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:gravity="center"
android:textAppearance="@style/TextAppearance.Design.Tab"/>
<TextView
android:id="@+id/indicator"
android:layout_width="24dp"
android:layout_height="24dp"
android:background="@drawable/background_indicator"
android:gravity="center"
android:lines="1"/>
</LinearLayout>
编辑
答案:
tab.setCustomView(R.layout.tab_proposed_rewards);
ColorStateList textColor = tabLayout.getTabTextColors();
TextView textView = (TextView) tab.getCustomView().findViewById(android.R.id.text1);
textView.setTextColor(textColor);
【问题讨论】:
-
答案在于here,第二个答案。使用您的styles.xml,这样您就可以使用
style标记通过xml 创建视图,而不是以编程方式创建它。就个人而言,我认为这是“更清洁”的方式。 -
@DillonBurton 自定义选项卡布局不起作用,但无论如何感谢您的帮助。我找到了不同的解决方案。
-
@AleksanderMielczarek 你是怎么做到的。我也陷入了困境。
标签: android android-layout tabs android-tablayout