android开发中经常会用到自定义view,今天我实现一个自定义view加上自定义的属性来对字体进行控制。
在编写自定义的view的时候,我们需要编写自己的view类,继承自view
在布局文件里引用我们自己定义好的view类
自定义的view,必须调用父类的两个构造方法:
public MyView(Context context) {
super(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
这里我的自定义view的名称叫做MyView,注意如果需要用自定义的属性的情况下,
public MyView(Context context, AttributeSet attrs)
这拥有两个参数的构造方法必须要重写,其实我们可以这么写,
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MyView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public MyView(Context context) {
this(context,null);
}
这里,其实不管调用的是那个构造方法,我们都将其运行三个参数的构造方法。
自定义属性的步骤:
1.在values目录下新建attrs.xml文件
<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();
}
设置相应的属性。
3.最后在布局文件中引用的时候需要加上自定义的命名空间:
xmlns:test="http://schemas.android.com/apk/res/com.example.selfview"
其中com.example.selfview是MyView类所在的包名
Test是我们在自定义中的属性的前缀:
<com.example.selfview.MyView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
test:textColor="#f57"
test:textSize="20px" />