本文实例讲述了Android自定义Button并设置不同背景图片的方法。分享给大家供大家参考,具体如下:
1、自定义MyButton类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
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控件一样。
1
2
3
4
|
< 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控件。
1
2
|
MyButton btn = (MyButton)findViewById(R.id.test_btn);
btn.onSetBmp(R.drawable.btn_d, R.drawable.btn_u);
|
其中btn_d表示为按下btn时背景图片,btn_u为默认状态下btn背景图片
希望本文所述对大家Android程序设计有所帮助。