天天看點

自定義View三個方法的意義

自定義 View 是每個Android 都經常接觸的,說來慚愧,我到現在對它的三個構造方法還是一知半解,平時隻 copy,接錯,現在好好補補這些基礎知識

很多時候系統自帶的View滿足不了設計的要求,就需要自定義View控件。

自定義View首先要實作一個繼承自View的類。添加類的構造方法,override父類的方法,如onDraw,(onMeasure)等。如果自定義的View有自己的屬性,需要在values下建立attrs.xml檔案,在其中定義屬性,同時代碼也要做修改。

1. 一個參數

第一屬于程式内執行個體化時采用,之傳入Context即可

public class MyView extends TextView{
    public MyView(Context context) {
       super(context);
       // TODO Auto-generated constructor stub
    }
}

public class NewView extends Activity
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_newview);
        setContentView(new MyView(this));

    }
}      

這樣一個簡單的自定義View就可以使用了。可以改變一下背景顔色,在MyView類中添加

protected void onDraw(Canvas canvas) {
   // TODO Auto-generated method stub
   super.onDraw(canvas);
   canvas.drawColor(Color.BLUE);
}      

2. 兩個參數

第二個用于layout檔案執行個體化,會把XML内的參數通過AttributeSet帶入到View内

public MyView(Context context,AttributeSet attrs){
       super(context, attrs);  
}

//命名空間,有了它,才能用自定義屬性
xmlns:test="http://schemas.android.com/apk/res-auto"

  <com.lizi.newset.customview.attrs.MyView
        android:id="@+id/myView"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        test:textSize="50px"
        test:textColor="#ff00ff"/>
    />      

values/attrs.xml 這個是自定義屬性的檔案

<declare-styleable name="MyView">
        <attr name="textColor" format="color"
        <attr name="textSize" format="dimension"
 </declare-styleable>      

完成上面的兩步之後就可以在代碼中執行個體化這個布局檔案了

setContentView(new MyView(this));      

自定義屬性代碼中示例:

;
        mPaint = new Paint();

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);
        int textColor = a.getColor(R.styleable.MyView_textColor, Color.BLACK);
        float textSize = a.getDimension(R.styleable.MyView_textSize, 36);

        mPaint.setTextSize(textSize);
        mPaint.setColor(textColor);
        a.recycle();      

官方解釋

Constructor that is called when inflating a view from XML. This is called when a view is being constructed from an XML file, supplying attributes that were specified in the XML file. This version uses a default style of 0, so the only attribute values applied are those in the Context’s Theme and the given AttributeSet

大緻應該是這個方法是通過xml檔案來建立一個view對象的時候調用。很顯然xml檔案一般是布局檔案,就是現實控件的時候調用,而布局檔案中免不了會有屬性的設定,如android:layout_width等,對這些屬性的設定對應的處理代碼也在這個方法中完成

3. 三個參數

第三個主題的style資訊,也會從XML裡帶入

public View (Context context, AttributeSet attrs,int