Android开发中,难免会遇到满足不了需求的控件,此时就需要自定来满足。
此处记录一下自定义View的开发过程:
1、开发前在attrs.xml中定义一下属性,自定义属性需要增加format属性,说明此属性是什么格式。
<declare-styleable name="MyView">
<attr name="textColor" format="color" />
<attr name="textSize" format="dimension" />
</declare-styleable>
2、java代码中进行实现
public class MyView extends View {
private Paint mPaint;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyView);//获得所有属性数组;
//通过TypedArray类的getXXXX()系列接口获得相应的值
float textSize = array.getDimension(R.styleable.MyView_textSize, 30);
int textColor = array.getColor(R.styleable.MyView_textColor, 0x990000FF);
mPaint.setTextSize(textSize);
mPaint.setColor(textColor);
array.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(new Rect(10, 10, 300, 300), mPaint);
}
}
3、layout布局中引入,主要是命名空间: xmlns:app="http://schemas.android.com/apk/res/com.dc.test",以及控件引入的属性: app:textColor="#678976"
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res/com.dc.test"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<com.hw.test.MyView
android:id="@+id/myll"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:textColor="#678976"
app:textSize="50sp" />
</RelativeLayout>
这样,一个简单的自定义控件就完成了。[流程]