作者:田字格 | 来源:互联网 | 2022-08-01 12:22
在Android开发中,往往要用到自定义的控件来实现我们的需求或效果。在使用自定义
控件时,难免要用到自定义属性,那怎么使用自定义属性呢?
在文件res/values/下新建attrs.xml属性文件,中定义我们所需要的属性。
<&#63;xml version="1.0" encoding="utf-8"&#63;>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public class CustomTextView extends TextView {
private int textSize;
private int textColor;
public CustomTextView(Context context, AttributeSet attrs) {
super (context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.custom_view);
textSize = ta.getDimensionPixelSize(R.styleable.custom_view_custom_size, 20 );
textColor = ta.getColor(R.styleable.custom_view_custom_color, 0x0000ff );
setColorAndSize(textColor, textSize);
ta.recycle();
}
public CustomTextView(Context context) {
super (context);
}
private void setColorAndSize( int textColor, int textSize) {
setTextColor(textColor);
setTextSize(textSize);
}
}
|
1 2 3 4 5 | <com.ldm.learn.customtextview android:layout_= "" android:text= "自定义TextView" ldm:custom_color= "#333333" ldm:custom_size= "35sp" >
</com.ldm.learn.customtextview></linearlayout>
|
布局说明:

通过以上几步就可以实现我们想要的自定义属性效果(用自定义属性设置文字大小及颜色)啦!