前言
今天封装View的时候,需要通过attr来改变textColor,但是TextColor的变换不像其他的内容如String,boolean等,直接用format标明就好,所以记录一下操作过程。
设置TextColor
设置textColor的标签不能像其他内容一样用format的一个属性,而是format要同时使用reference和color的属性。
<declare-styleable name="myView">
<attr name="textColor" format="reference|color"/> <!-- 字色-->
</declare-styleable>
然后在调用的时候才能填写对应的内容。
两种format中,reference对应某种资源文件的id,我们添加了它,就可以填写drawable包内的内容,如果你的textcolor需要在不同情况下显示不同的颜色,就需要用到format的reference和 drawable的selector。
<com.example.myapplication.base.myView
android:id="@+id/myView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:textColor="@drawable/selector_text_color"
/>
color对应某种实体颜色,填了它可以直接填写颜色的id或者@color下的某个颜色。
<com.example.myapplication.base.myView
android:id="@+id/myView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:textColor="@color/black"
/>
接下来在代码中,用ColorStateList类或者int来获取颜色实例即可。
private void initView(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.myView);
// 用int变量获取
int color = typedArray.getColor(R.styleable.myView_textColor, 0);
if (color != 0) textView.setTextColor(color);
//用ColorStateList类获取
ColorStateList colorStateList = typedArray.getColorStateList(R.styleable.myView_textColor);
if (colorStateList != null) textView.setTextColor(colorStateList);
}
如果用selector设置多个颜色的情况下,ColorStateList可以全部获取,而int只能获取其中一个(默认的那个),所以建议用ColorStateList。
TextView的相关源码
在源码的attrs.xml文件中,textColor的format就包含了reference和color两个元素。
<!-- Color of text (usually same as colorForeground). -->
<attr name="textColor" format="reference|color" />
<!-- Color of highlighted text. -->
<attr name="textColorHighlight" format="reference|color" />
<!-- Color of hint text (displayed when the field is empty). -->
<attr name="textColorHint" format="reference|color" />
<!-- Color of link text (URLs). -->
<attr name="textColorLink" format="reference|color" />
在TextView类中,setTextColor包含了两个同名方法。
public class TextView extends View implements ViewTreeObserver.OnPreDrawListener {
......省略无关代码......
public void setTextColor(@ColorInt int color) {
mTextColor = ColorStateList.valueOf(color); // 本质还是用了ColorStateList类
updateTextColors();
}
@android.view.RemotableViewMethod
public void setTextColor(ColorStateList colors) {
if (colors == null) {
throw new NullPointerException();
}
mTextColor = colors;
updateTextColors();
}
}