Android Resources小研究
研究了一下如何获取各种资源,这里用颜色举例,其他类型没有尝试,但应该大同小异。
我们在styles.xml设置<item name="colorPrimary">@color/colorPrimary</item>。
R.color.colorPrimary -> Color Int
ContextCompat.getColor(context, R.color.colorPrimary) -> Color Int
R.attr.colorPrimary -> Color Int
这里的Context需要带Theme的Context,比如是一个ContextThemeWrapper或是Activity/View的Context,不然什么也拿不到。下个例子同理。
| 1 | 
 | 
然后context.themeColor(R.attr.colorPrimary) -> Color Int
R.attr.colorPrimary -> R.color.colorPrimary(Color Res)
| 1 | 
 | 
然后context.themeRes(R.attr.colorPrimary) -> R.color.colorPrimary
一个更有用的例子是context.themeRes(R.attr.colorControlActivated) -> R.color.colorAccent(通常情况下是这个值)
拦截View
比如拦截Button的android:textColor和app:backgroundTint。
首先继承AppCompatButton或MaterialButton。
新建attrs.xml并塞入:
| 1 | <declare-styleable name="Theme_Button"> | 
然后就可以
| 1 | context.withStyledAttributes(set, attrs, defStyleAttr, defStyleRes) { |