我們在自定義控件的時候送火,通常需要定義一些屬性提供給用戶屡萤,類似于一個接口姻氨,方便用戶直接在xml文件中直接設(shè)置某些屬性的值蝙搔。
一缕溉、在attrs中自定義屬性
在res/values下的atts.xml中定于你需要的屬性。如果沒有這個文件吃型,那么就需要你在values下新建一個attrs.xml資源文件
這個attrs.xml文件內(nèi)容通常是下面這種格式:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="myTextSize" format="dimension"/>
<attr name="myColor" format="color"/>
</declare-styleable> ?
</resources>?
- <declare-styleable name="MyView"> 中給自己定義的屬性所應用的控件起一個名字证鸥,這個名字用來在自定義控件中獲取這個屬性。
- <attr name="myColor" format="color"/> 自定義你需要的屬性名稱勤晚,以及這個屬性的類型枉层。
- 一般屬性的類型有下面這幾種:
- color:顏色值
- boolean:布爾值
- dimesion:尺寸值
- float:浮點值
- integer:整型值
- string:字符串
- fraction:百分數(shù)
- enum:枚舉值
- reference:引用資源文件
二、在布局文件中使用自定義的屬性
在我們使用自定義控件的布局文件中使用赐写。
代碼如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/com.eyu.attrtextdemo"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<com.eyu.attrtextdemo.MyView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
myapp:myTextSize="20sp"
myapp:myColor="#324243"/>
</LinearLayout>
第一步:加入命名空間鸟蜡。格式如下
xmlns:起一個名字="http://schemas.android.com/apk/res/你的包名"
或者
xmlns:起一個名字="http://schemas.android.com/apk/res-auto"
第二步:在控件中使用。格式如下
命名空間的名字.自定義屬性的名字 = "對應屬性的值"
三挺邀、java代碼中獲取自定義屬性的值
在java代碼中獲取用戶設(shè)置的屬性的值揉忘,然后用這些值來初始化一些參數(shù)。
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.MyView);
int textColor = a.getColor(R.styleable.MyView_myColor, 003344);
float textSize = a.getDimension(R.styleable.MyView_myTextSize, 33);
paint.setTextSize(textSize);
paint.setColor(textColor);
a.recycle();
}
在自定義控件中三個方法的構(gòu)造函數(shù)中悠夯,獲取屬性
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.這里就說自定義屬性分類的名字);
int textColor = a.getColor(R.styleable.屬性分類名_屬性名, 默認值);
取到這些值就可以使用了癌淮。