我试图制作一个棘手的布局,为此我需要 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/