Android methods for customizing Button and setting different background images
- 2021-01-02 21:59:17
- OfStack
This article shows how Android can customize Button and set different background images. To share for your reference, the details are as follows:
1. Custom MyButton class
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. Add MyButton control to the xml layout file, just like applying normal Button control 1.
<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 is the package name where you define the MyButton class
3. Load MyButton controls in onCreate().
MyButton btn = (MyButton)findViewById(R.id.test_btn);
btn.onSetBmp(R.drawable.btn_d, R.drawable.btn_u);
btn_d is the background image when btn is pressed, and btn_u is the default background image of btn
For more information about Android controls, please visit our special topic: Summary of Android Controls usage.
I hope this article has been helpful in Android programming.