android 如何自定义view

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();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值