xmlns:my=http://schemas.android.com/apk/res/com.example.xhelloworld
<com.example.xhelloworld.MyView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
my:textColor="#FFFFFFFF"
my:textSize="22dp"
/>
注:这步我在实现的时候出错,问题是显示找不到属性textColor和textSize,这奇怪的错误。解决方法是,在写my:textColor="#FFFFFFFF" 时,写到my之后,按alt+/,这是会自动添加一个xmlns,和my的路径是一样的,用生成的这个替换掉my就可以了。
3)设置完属性之后,当然还要对其进行处理。在自定义View类中的构造方法中进行处理
public MyView(Context context,AttributeSet attrs){
super(context, attrs);
mPaint = new Paint();
//TypedArray是一个用来存放由context.obtainStyledAttributes获得的属性的数组
//在使用完成后,一定要调用recycle方法
//属性的名称是styleable中的名称+“_”+属性名称
//TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyView);
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyView);
int textColor = array.getColor(R.styleable.MyView_textColor, 0XFF00FF00); //提供默认值,放置未指定
float textSize = array.getDimension(R.styleable.MyView_textSize, 36);
mPaint.setColor(textColor);
mPaint.setTextSize(textSize);
array.recycle(); //一定要调用,否则这次的设定会对下次的使用造成影响
}
4、背后的事
View类的构造方法:
·public view(Context context) 当在代码中创建对象时会被调用
·public View (Context context, AttributeSet attrs)
官方的文档是:
Constructor that is called when inflating a view from XML. This is called when a view is being constructed from an XML file, supplying attributes that were specified in the XML file. This version uses a default style. of 0, so the only attribute values applied are those in the Context's Theme and the given AttributeSet
大致应该是这个方法是通过xml文件来创建一个view对象的时候调用。很显然xml文件一般是布局文件,就是现实控件的时候调用,而布局文件中免不了会有属性的设置,如android:layout_width等,对这些属性的设置对应的处理代码也在这个方法中完成。