我们都会自定义控件,然后在xml文件当中调用、进行布局。然而系统给定的xml属性往往不能满足我们的要求,因此我们需要自定义属性。例如我们需要为我们的自定义控件MyView自定义一个显示文字的属性。那么,我们需要在values/attrs.xml进行如下编辑:
<resources>
<declare-styleable name="MyView">
<attr name="myText" format="string" />
<attr name="myTextcolor" format="reference|color" />
</declare-styleable>
</resources>
其中styleable name一般取跟自定义控件一样的名字。我定义了两个xml属性:第一个是myText,因为format是string,所以调用该属性的时候,相应内容填字符串;第二个是myTextcolor,同理调用该xml属性的时候,相应的内容得是应用资源或者颜色值。
format 参考: reference:参考某一资源ID; color:颜色值; boolean:布尔值; dimension:尺寸值; float:浮点值; integer:整型值; string:字符串 ;fraction:百分数; enum:枚举值。自定义控件MyView的类中将自定义xml属性值提取出来,分别赋值给textContext和textColor,然后将textContext作为画笔要画的内容,而textColor作为画笔颜色。代码给出:
public class MyView extends View {
String textContext;
Paint mTextPaint;
int textColor;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray=context.obtainStyledAttributes(attrs,R.styleable.MyView);
textContext=typedArray.getString(R.styleable.MyView_myText);
textColor=typedArray.getInteger(R.styleable.MyView_myTextcolor,Color.BLUE);
typedArray.recycle();
// 初始化画笔
mTextPaint=new Paint();
// 画笔颜色
mTextPaint.setColor(textColor);
// 画笔画出来的文字大小
mTextPaint.setTextSize(34);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText(textContext, 0,0, mTextPaint);
}
}
xml布局文件如下,自定义控件调用了之前说的两个自定义xml属性:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.example.ies171226.hunatest.MyView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:myText="helloworld"
app:myTextcolor="@color/colorAccent" />
</LinearLayout>
注意要加上命名空间:xmlns:app="http://schemas.android.com/apk/res-auto"。com.example.ies171226.hunatest是MyView所在包的包名。程序运行结果是一行红色字体:helloword。