自定義控件可能會有很多種方法,這裏只介紹我要介紹的方法.
在這種方法中,大概的步驟是這樣的
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);