Android 自訂群組件(一) 基本實現方式和自訂屬性

來源:互聯網
上載者:User

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


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.