转载请注明出处
1、自定义MyButton类
public class MyButton extends Button {
//This constructormust be
public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyButton(Context context) {
super(context);
}
private Paint mPaint = null;
private String mText;
private int mX, mY;
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;
}
private int mDownBmpId, mUpBmpId;
public void onSetBmp(int nDownID, int nUpID) {
this.mDownBmpId = nDownID;
this.mUpBmpId = nUpID;
}
@Override
public void onDraw(Canvas canvas) {
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);
}
}
2、 在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类所在的包名
3、在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背景图片