android - 获取Android默认Tab指示器颜色

标签 android xml

我试图制作一个棘手的布局,为此我需要 Android 的默认选项卡指示器颜色。

我搜索了很多,但在每一个地方我都找到了如何更改和自定义选项卡指示器,但找不到如何获取默认选项卡指示器的十六进制颜色代码。

最佳答案

我针对您的问题做了一些研究,希望这对您有所帮助。

选项卡指示器颜色在 TabLayout (Code) 类的内部类 SlidingTabStrip 中设置.很遗憾,您无法访问此变量。

private class SlidingTabStrip extends LinearLayout {

    private final Paint mSelectedIndicatorPaint;

    // ...

    void setSelectedIndicatorColor(int color) {
        if (mSelectedIndicatorPaint.getColor() != color) {
            mSelectedIndicatorPaint.setColor(color);
            ViewCompat.postInvalidateOnAnimation(this);
        }
    }
}

但是在 TabLayout 的构造函数中设置了默认的选项卡指示器颜色。

public TabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    // Add the TabStrip
    mTabStrip = new SlidingTabStrip(context);
    addView(mTabStrip, LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TabLayout, defStyleAttr, R.style.Widget_Design_TabLayout);

    // <-- HERE
    mTabStrip.setSelectedIndicatorColor(a.getColor(R.styleable.TabLayout_tabIndicatorColor, 0));    
}

我认为您需要访问 R.styleable.TabLayout_tabIndicatorColor得到你想要的。我现在无法测试它是否有效以及如何工作,但我希望这对您有所帮助。

更新

我在家里试过这个,似乎很管用。我在 Activity 的 onCreate() 方法中使用了这段代码

TypedArray a = getContext().obtainStyledAttributes(null, R.styleable.TabLayout, 0, R.style.Widget_Design_TabLayout);
// returns -16738680 in my case which is the accentColor
int color = a.getColor(R.styleable.TabLayout_tabIndicatorColor, 0); 

但我看到,R.styleable.TabLayout_tabIndicatorColor 只是链接到 accentColor。也许这是获得您想要的东西的更好方法。

<style name="Base.Widget.Design.TabLayout" parent="android:Widget">
    <item name="tabIndicatorColor">?attr/colorAccent</item>
    <!-- other items -->
</style>

关于android - 获取Android默认Tab指示器颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36469795/

相关文章:

ios - 如何使用 RestKit 0.20.1 发送 XML 格式的 POST 请求

android - 在android中填充没有XML文件的弹出菜单

android - 如何在圆上画新月形状

Android启动ActionBarActivity先显示空页

android - 无法滚动 RecyclerView,当尝试在滚动时隐藏工具栏

c++ - wistringstream 从一个 xml 文件到一个整数?

c# - 使用 C# 将 XML 转换为字符串

android - Android Wear Preview 的语音输入

android - 在自定义进度条中,白色背景在 Android 中显示。如何删除它?

javascript - 从 Tropo API 接收 JSON(不是 XML)时出现问题