android 如何自定义view

时间:2023-02-09 20:41:01
1. 首先在 attrs.xml 中声明自定义view要自定义的属性:
    <declare-styleable name="CustomTextView">
<attr name="titleText" format="string"></attr>
<attr name="titleTextColor" format="color"></attr>
        <attr name="titleTextSize" format="dimension"></attr>
    </declare-styleable>
    

    注意:

(1) name 不是 android:name

    (2) format一共有:string, color, dimension, integer, enum, reference, float, boolean, fraction, flag, 

各个类型的含义可以参考这个文章:http://blog.csdn.net/ethan_xue/article/details/7315064

2. 在XML引用(引入命名空间,注意最后是包名):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res/com.zmq.test"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >
    <com.geak.test.CustomTextView
        android:layout_width="120dip"
        android:layout_height="120dip"
        android:background="#ffffff"
        custom:titleText="ABCDEFG"
        custom:titleTextColor="#00ff00"
        custom:titleTextSize="13sp">
    </com.geak.test.CustomTextView>
</LinearLayout>

3. 初始化构造函数差读取自定义属性值:

public class CustomTextView extends TextView {

    private String text;
    private int color;
    private int size;
    
public CustomTextView(Context context) {
this(context, null);
}

public CustomTextView(Context context, AttributeSet attrs) {//  此构造函数必走
this(context, attrs, 0);
}

public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, 0);

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView, defStyle, 0);
text = a.getString(R.styleable.CustomTextView_titleText);
color = a.getColor(R.styleable.CustomTextView_titleTextColor, Color.BLACK);
size = a.getDimensionPixelSize(R.styleable.CustomTextView_titleTextSize, 13);
setText(text);
setTextColor(color);
setTextSize(size);
a.recycle();
}
}