前言
前幾天阿里的面試官問(wèn)了我一個(gè)問(wèn)題蚀腿,如何實(shí)現(xiàn)自定義View的自定義屬性嘴瓤,我第一感覺(jué)是很熟悉,但卻答不上來(lái)莉钙±啵看來(lái)有必要記錄一下。
實(shí)現(xiàn)
自定義一個(gè)View類
這里我舉個(gè)簡(jiǎn)單的例子磁玉,自定義TextView :
MyTextView.java
public class MyTextView extends TextView {
public MyTextView(Context context) {
super(context);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
將自定義的View類放到layout中
仍然很簡(jiǎn)單
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.attrtest.MyTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="自定義屬性" />
</LinearLayout>
創(chuàng)建自定義屬性
在/res/values/下新建attr.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyTextView">
<attr name="color" format="color" />
<attr name="size" format="dimension" />
</declare-styleable>
</resources>
這里有一個(gè)域declare-styleable(聲明屬性)停忿,它有一個(gè)name屬性MyTextView,這個(gè)name屬性其實(shí)就是這個(gè)屬性在R類中的id蚊伞。這里有兩個(gè)attr域席赂,他們都有兩個(gè)屬性,name就不說(shuō)了厚柳,format表示這個(gè)屬性的類型氧枣,目前已知的屬性有這些:
reference// 資源類型,通常是@開(kāi)頭别垮,例如@+idxx便监,@idxx
string// 字符串類型,通常是文字信息
dimension// 浮點(diǎn)類型碳想,通常是尺寸度量烧董,單位有很多px,dp胧奔,sp等
color// 顏色類型逊移,通常是顏色16進(jìn)制代碼,支持ARGB
boolean// 布爾類型龙填,true和false
enum// 枚舉類型胳泉,通常是代表這個(gè)屬性提供了幾種值來(lái)進(jìn)行選擇拐叉,并且只能選擇這幾種中的一個(gè)
flag// 與enum基本沒(méi)有區(qū)別
integer// 整數(shù)類型,通常是整數(shù)
在layout中添加自定義屬性
public class MyTextView extends TextView {
public MyTextView(Context context) {
super(context);
}
@SuppressLint("Recycle")
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray t = getContext().obtainStyledAttributes(attrs,
R.styleable.MyTextView);
int textColor = t.getColor(R.styleable.MyTextView_color, Color.BLACK);
float textSize = t.getDimension(R.styleable.MyTextView_size, 10);
this.setTextColor(textColor);
this.setTextSize(textSize);
}
public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
使用getContext方法得到當(dāng)前Context扇商,調(diào)用Context.obtainStyledAttributes方法凤瘦,傳入AttributeSet和R.styleable.MyTextView案铺,這里的R.styleable.MyTextView蔬芥,就是我們?cè)赼ttrs.xml中定義的名稱,通過(guò)R.styleable來(lái)訪問(wèn)控汉。
方法返回一個(gè)TypedArray對(duì)象笔诵。按照attrs,xml中定義的屬性的類型,使用不同的get方法獲取指定屬性的值姑子。
截圖
遷移自我的CSDN博客
2015.03.23