自訂view中自訂屬性的用法.,自訂view
有時候我們自訂的view需要用到有自己定義的屬性。
首先定義自己的屬性,在res/values/attrs.xml中定義,xml檔案如下:
<?xml version="1.0" encoding="utf-8"?><resources> <declare-styleable name = "myView"> <attr name = "text" format = "string" /> <attr name = "textSize" format = "dimension"/> <attr name = "textColor" format = "color"/> <attr name = "rectColor" format = "color"/> </declare-styleable></resources>
name屬性很重要,關係到以後的調用。
format為屬性的類型,這裡列舉了幾種基本的資料類型,注意textSize等關係到大小的屬性格式為dimension。
在布局檔案中的使用。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:my="http://schemas.android.com/apk/res/com.example.myview" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" > <com.example.myview.MyView android:layout_width="100dp" android:layout_height="100dp" my:text = "點擊開始計數" my:textColor = "#ffff0000" my:textSize = "21sp" my:rectColor = "#ff00ff00" /></RelativeLayout>
xmlns:my="http://schemas.android.com/apk/res/com.example.myview" 為使用
my欄位調用自訂屬性的關鍵代碼。
使用my:XXX時並不會驗證屬性的正確性。
但是在自訂view代碼中擷取屬性值的時候會進行驗證。
擷取屬性值對自定view進行初始化。
//擷取xml檔案中的屬性數組private void initAttrs(AttributeSet attrs) {mPanit = new Paint();mBound = new Rect();setOnClickListener(this);//和attr.xml中的屬性列表對應上TypedArray ta = getContext().obtainStyledAttributes(attrs,R.styleable.myView);String text = ta.getString(R.styleable.myView_text);setText(text);int textSize = ta.getDimensionPixelOffset(R.styleable.myView_textSize, 26);setTextSize(textSize);int color = ta.getColor(R.styleable.myView_textColor, 0xff000000);setTextColor(color);int rectColor = ta.getColor(R.styleable.myView_rectColor, 0xff000000);setRectColor(rectColor);ta.recycle();}AttributeSet attrs為xml中的屬性和它所對應的值。
TypedArray ta = getContext().obtainStyledAttributes(attrs,R.styleable.myView);
只擷取自訂屬性名為myView中的屬性。並且賦值給TypeArray ta。
之後便可根據 ta 擷取擷取對應的屬性值了。
至於擷取的屬性值該怎麼用,就要看你自己的了。
android自訂控制項怎自訂屬性?
可以在attrs.xml中定義自己的屬性。不過這種自訂的東西還是寫在代碼裡比較好,動態載入,方便控制。
android自訂view 屬性使用問題
不可以,自訂的只能運行了看,只有系統的才可以在Graphical Layout模式下看