日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

android 参数 attrs.xml,使用attrs.xml自定义属性

發布時間:2024/9/27 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 android 参数 attrs.xml,使用attrs.xml自定义属性 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

控件有很多屬性,如android:id、android:layout_width、android:layout_height等,但是這些屬性都是系統自帶的屬性。使用attrs.xml文件,可以自己定義屬性。本文在Android自定義控件的基礎上,用attrs.xml文件自己定義了屬性。

首先,在values文件夾下,新建一個attrs.xml文件,文件內容如下:

其中,表明樣式名稱為CustomView,下面包含了兩個自定義屬性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兩個屬性。

CustomView.java的構造函數:

// 構造函數

public CustomView(Context context, AttributeSet attrs) {

super(context, attrs);

// 獲得TypedArray

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);

// 獲得attrs.xml里面的屬性值,格式為:名稱_屬性名,后面是默認值

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

// 返回一個綁定資源結束的信號給資源

a.recycle();

}

首先從R.styleable.CustomView獲得了TypedArray變量,再用getColor(),getDimension()等方法獲取相應的屬性值,屬性格式為“樣式名_屬性名”,屬性后面的參數是默認值。獲得屬性值以后,就可以應用這些屬性值。recycle()方法用于返回信號給資源(不懂什么意思)。

運行結果如下:

總結

以上是生活随笔為你收集整理的android 参数 attrs.xml,使用attrs.xml自定义属性的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。