在Android设计库TabLayout中选择时更改图标和标题颜色

Vis*_*kar 6 android android-tablayout

我正在使用TabLayout设计库我想要实现的是

我想实现

我已经尝试了很多教程,我可以通过自定义选项卡来实现它,但是当选择选项卡时会出现限制我想要更改文本颜色以及图标的图像,这是通过引用无法实现的到目前为止我读过的任何教程.到目前为止,我已经尝试过这个了FragmentStatePagerAdapter

public View getTabView(int position) {
    View tab = LayoutInflater.from(mContext).inflate(R.layout.tabbar_view, null);
    TextView tabText = (TextView) tab.findViewById(R.id.tabText);
    ImageView tabImage = (ImageView) tab.findViewById(R.id.tabImage);
    tabText.setText(mFragmentTitles.get(position));
    tabImage.setBackgroundResource(mFragmentIcons.get(position));
    if (position == 0) {
        tab.setSelected(true);
    }
    return tab;
}
Run Code Online (Sandbox Code Playgroud)

Ped*_*dro 2

设计库已更新,以匹配材料设计“带有图标和文本的选项卡”规范,因此您不需要自定义选项卡视图。

但在当前版本 (23.1.1) 中,只有文本颜色符合规范(选项卡聚焦 - #fff,选项卡未聚焦 - 70% #fff)。因此,您可以使用ColorStateList返回的 bygetTabTextColors()为图标着色DrawableCompat.setTintList(ColorStateList)

尝试使用这个要点https://gist.github.com/mikovali/7a89b505cd6306bb94a8。删除该行tabs.setTabTextColors(Color.RED, Color.GREEN)应该足以匹配深色工具栏上的文本和图标的规范。