Android使用AttributeSet自定義控件的方法

所謂自定義控件(或稱組件)也就是編寫自己的控件類型,而非Android中提供的標準的控件,如TextView,CheckBox等等.不過自定義的控件一般也都是從標準控件繼承來的,或者是多種控件組合,或者是對標準控件的屬性進行改變而得到的自己滿意的控件.

    自定義控件可能會有很多種方法,這裏只介紹我要介紹的方法.

 

    在這種方法中,大概的步驟是這樣的

    1.我們的自定義控件和其他的控件一樣,應該寫成一個類,而這個類的屬性是是有自己來決定的.

    2.我們要在res/values目錄下建立一個attrs.xml的文件,並在此文件中增加對控件的屬性的定義.

    3.使用AttributeSet來完成控件類的構造函數,並在構造函數中將自定義控件類中變量與attrs.xml中的屬性連接起來.

    4.在自定義控件類中使用這些已經連接的屬性變量.

    5.將自定義的控件類定義到佈局用的xml文件中去.

    6.在界面中生成此自定義控件類對象,並加以使用.

 

    好了,按照上述的方法,我們來看看http://blog.csdn.net/Android_Tutor/archive/2010/04/20/5508615.aspx

    博客中的實例代碼,按步驟加以解釋:

    //---------------------------------------------------------------------------------

    1. 定義自己的控件類:--------------------------------------------代碼1.

    package com.android.tutor;  
    import android.content.Context;  
    import android.content.res.TypedArray;  
    import android.graphics.Canvas;  
    import android.graphics.Color;  
    import android.graphics.Paint;  
    import android.graphics.Rect;  
    import android.graphics.Paint.Style;  
    import android.util.AttributeSet;  
    import android.view.View;  

 
    public class MyView extends View
    {  
        private Paint mPaint;  
        private Context mContext;  
        private static final String mString = "Welcome to Mr Wei's blog";  
      
        public MyView(Context context)
        {  
            super(context);  
            mPaint = new Paint();  
        }  

 
        public MyView(Context context,AttributeSet attrs)  
        {  
            super(context,attrs);  
            mPaint = new Paint();  
          
            TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.MyView);             
            int textColor = a.getColor(R.styleable.MyView_textColor,0XFFFFFFFF);  
            float textSize = a.getDimension(R.styleable.MyView_textSize, 36);  
          
           

發佈了19 篇原創文章 · 獲贊 5 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章