在我们写布局文件时,像button,ImageView,都是一个个view。那自定义view就可以理解为,”newbutton“或者"newiamgeView"。
那么在button类似的组件中,我们通过设置width,hight就可以改变他们的大小,这些属性当然是前辈们完成好,供我们使用的。
那现在我们想给我们自定义的view,添加一个属性,比如一个文本字体大小,或者文本的字体颜色,那要怎么做呢。可能你会想,咦为什么不直接写android:textSize=""这样去设置呢,那如果你这个View并没有像button有text这个属性,你又怎么设置呢。
好比你这个view中,定义了一个paint,想用paint画一个蓝色的园,那你还想android:textColor=“”去设置吗?明显是不行的嘛。
那又有同学想了,那简单啊就在onDraw直接定义就好了。
protected void onDraw(Canvas canvas){
paint.setColor(Color.BLUE);
}
但,你们想想看一个属性如果写死的话,那这个view就不好用了,比如你想设置button的width,然而它是写死的,你还会用它吗,是一个道理。
那要怎么实现属性的自定义呢。首先你需要
- 在res/values文件下定义一个attrs.xml文件.代码如下:
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <declare-styleable name="MyView">
- <attr name="textColor" format="color" />
- <attr name="textSize" format="dimension" />
- </declare-styleable>
- </resources>
然后在myView的构造函数中去获得
- public MyView(Context context,AttributeSet attrs)
- {
- super(context,attrs);
- mPaint = new Paint();
- //
- TypedArray a = context.obtainStyledAttributes(attrs,
- R.styleable.MyView);
- int textColor = a.getColor(R.styleable.MyView_textColor,
- 0XFFFFFFFF);
- float textSize = a.getDimension(R.styleable.MyView_textSize, 36);
- mPaint.setTextSize(textSize);
- mPaint.setColor(textColor);
- a.recycle();
- }
可能有同学奇怪你这步不也是写死了的吗,其实最后这个参数是默认值,就是不去设置时取这个值
- int textColor = a.getColor(R.styleable.MyView_textColor,
- 0XFFFFFFFF);
然后在xml文件的使用。
<?xml
version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:test="http://schemas.android.com/apk/res/com.android.tutor"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<com.android.tutor.MyView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
test:textSize="20px"
test:textColor="#fff"
/>
</LinearLayout>
上述的代码来自 http://weizhulin.blog.51cto.com/1556324/311453