1. 程式人生 > >關於自定義view的一些問題

關於自定義view的一些問題

最近遇到了較為棘手的重寫view的問題。首先是寫構造方法。按照原生的寫法是單引數構造方法呼叫自己的雙引數構造方法,雙引數構造方法呼叫自己的三個引數的構造方法,而不能使用像編譯器推薦的那樣只調用父類的構造方法。按照原生view的寫法初始化只需在三個引數的構造方法中完成即可,而不用每個構造方法都寫一遍。

關於屬性的宣告。我們可以在attrs.xml中定義一些我們需要的屬性,用<attr>定義。如果集中起來可以形成一個<declare-styleable>,這個同樣放在attr.xml中。若需要在layout的xml中引用,則需要宣告

<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:erone="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent">
後面即可用erone:xxxx=""來使用屬性了。

關於屬性的讀取。參照原始碼,我們可以如下寫

final Resources.Theme theme = context.getTheme();
TypedArray a = theme.obtainStyledAttributes(
        attrs, 
R.styleable.Erone, defStyleAttr, 0); int n = a.getIndexCount(); for (int i = 0; i < n; i++) { int attr = a.getIndex(i); switch (attr) { case xxx: int c=a.getColor(attr,0); break; case xxx1: float d=a.getDimension(attr,0); break;
} } a.recycle();
其中R.styleable.Erone是我在attr定義的一個<declare-styleable>屬性集合的名字,代表你要尋找在這底下被定義的屬性,switch判斷屬性id後即可拿到對應的值