android 参数 attrs.xml,使用attrs.xml自定义属性
控件有很多屬性,如android:id、android:layout_width、android:layout_height等,但是這些屬性都是系統(tǒng)自帶的屬性。使用attrs.xml文件,可以自己定義屬性。本文在Android自定義控件的基礎(chǔ)上,用attrs.xml文件自己定義了屬性。
首先,在values文件夾下,新建一個(gè)attrs.xml文件,文件內(nèi)容如下:
其中,表明樣式名稱為CustomView,下面包含了兩個(gè)自定義屬性tColor和tSize,其中tColor是顏色(color)類的屬性,tSize是尺寸(dimension)類的屬性。
主窗體的布局文件如下:
xmlns:tools="http://schemas.android.com/tools"
xmlns:test="http://schemas.android.com/apk/res/com.hzhi.customview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
android:id="@+id/cusView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
test:tColor="#00FFFF"
test:tSize="30dp"
>
定義了xmlns:test="http://schemas.android.com/apk/res/com.hzhi.customview"(其中com.hzhi.customview是包名),在控件屬性中就可以增加test:tColor和test:tSize兩個(gè)屬性。
CustomView.java的構(gòu)造函數(shù):
// 構(gòu)造函數(shù)
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
// 獲得TypedArray
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
// 獲得attrs.xml里面的屬性值,格式為:名稱_屬性名,后面是默認(rèn)值
int tColor = a.getColor(R.styleable.CustomView_tColor, Color.GREEN);
float tSize = a.getDimension(R.styleable.CustomView_tSize, 35);
p.setColor(tColor);
p.setTextSize(tSize);
// 返回一個(gè)綁定資源結(jié)束的信號(hào)給資源
a.recycle();
}
首先從R.styleable.CustomView獲得了TypedArray變量,再用getColor(),getDimension()等方法獲取相應(yīng)的屬性值,屬性格式為“樣式名_屬性名”,屬性后面的參數(shù)是默認(rèn)值。獲得屬性值以后,就可以應(yīng)用這些屬性值。recycle()方法用于返回信號(hào)給資源(不懂什么意思)。
運(yùn)行結(jié)果如下:
總結(jié)
以上是生活随笔為你收集整理的android 参数 attrs.xml,使用attrs.xml自定义属性的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 可优比和aag哪个好_火花塞多级和单级哪
- 下一篇: Java-标识符和关键字