Android 自訂群組件(一) 基本實現方式和自訂屬性
實現方式:
1. 繼承自ViewGroup或Layout ,自訂設定子view的位置、尺寸等,用於組合一些組件,產生一個複合組件
2. 繼承自已有的widget View,用於擴充現有組件的功能
3. 繼承自View ,完全自訂一個組件
自訂類的建構函式:
public CustomView2(Context context) {//直接在代碼中調用時,使用該函數super(context);}public CustomView2(Context context, AttributeSet attrs) {//在xml中使用自訂view時,使用這個函數super(context, attrs);}public CustomView2(Context context, AttributeSet attrs, int defStyle) {//可以由上一個函數中手動調用super(context, attrs, defStyle);} 自訂函數中的attrs表示view的屬性集,defStyle表示預設的屬性資源集的id
在xml中使用自訂view的流程:
自訂屬性定義屬性res/values/attrs.xml
布局中使用
代碼中解析自訂屬性
public CustomView1(Context context, AttributeSet attrs) {super(context, attrs);//atts 包括TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.customview1);//系統會在自訂屬性前加上它所屬的declare-styleable 的name_int color = array.getColor(R.styleable.customview1_color, Color.WHITE);float rotation = array.getFloat(R.styleable.customview1_rotation, 0f);float score = array.getFraction(R.styleable.customview1_score, 0, 13, 10);array.recycle();//回收System.out.println("color=" + color + ", rotation=" + rotation + ", score=" + score);setBackgroundColor(color);}