一、自定義MyButton類android
public class MyButton extends Button {canvas
//This constructormust beide
public MyButton(Context context, AttributeSet attrs) { super(context, attrs); }佈局
public MyButton(Context context) { super(context); }this
private Paint mPaint = null; private String mText; private int mX, mY;spa
public void onSetText(String text, int nLeft, int nBottom, int nTextSize, int nTextColor) { mPaint = new Paint(); mPaint.setTextSize(nTextSize); mPaint.setColor(nTextColor); this.mText = text; this.mX = nLeft; this.mY = nBottom; }xml
private int mDownBmpId, mUpBmpId;圖片
public void onSetBmp(int nDownID, int nUpID) { this.mDownBmpId = nDownID; this.mUpBmpId = nUpID; }get
@Override public void onDraw(Canvas canvas) {io
if (mPaint != null) canvas.drawText(mText, mX, mY, mPaint); super.onDraw(canvas); }
@Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { super.setBackgroundResource(mDownBmpId); } else if (event.getAction() == MotionEvent.ACTION_UP) { super.setBackgroundResource(mUpBmpId); } return super.onTouchEvent(event); } }
二、 在xml佈局文件中添加MyButton控件,像應用普通的Button控件同樣。
<com.MyButton android:id="@+id/test_btn" android:layout_width="120px" android:layout_height="fill_parent" android:text="Test" android:background="@drawable/btn_u" />
其中com.MyButton是你定義的MyButton類所在的包名
三、在onCreate()中加載MyButton控件。
MyButton btn = (MyButton)findViewById(R.id.test_btn); btn.onSetBmp(R.drawable.btn_d, R.drawable.btn_u);
其中btn_d表示爲按下btn時背景圖片,btn_u爲默認狀態下btn背景圖片