所謂自定義控件(或稱組件)也就是編寫自己的控件類型,而非Android中提供的標(biāo)準(zhǔn)的控件,如TextView,CheckBox等等.不過自定義的控件一般也都是從標(biāo)準(zhǔn)控件繼承來的,或者是多種控件組合,或者是對標(biāo)準(zhǔn)控件的屬性進(jìn)行改變而得到的自己滿意的控件.
自定義控件可能會有很多種方法,這里只介紹我要介紹的方法.
在這種方法中,大概的步驟是這樣的
1.我們的自定義控件和其他的控件一樣,應(yīng)該寫成一個類,而這個類的屬性是是有自己來決定的.
2.我們要在res/values目錄下建立一個attrs.xml的文件,并在此文件中增加對控件的屬性的定義.
3.使用AttributeSet來完成控件類的構(gòu)造函數(shù),并在構(gòu)造函數(shù)中將自定義控件類中變量與attrs.xml中的屬性連接起來.
4.在自定義控件類中使用這些已經(jīng)連接的屬性變量.
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);