自定义View的自定义属性attrs中如何设置Textcolor

前言

今天封装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();
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值