手机
当前位置:查字典教程网 >编程开发 >安卓软件开发 >Android自定义Button并设置不同背景图片的方法
Android自定义Button并设置不同背景图片的方法
摘要:本文实例讲述了Android自定义Button并设置不同背景图片的方法。分享给大家供大家参考,具体如下:1、自定义MyButton类publ...

本文实例讲述了Android自定义Button并设置不同背景图片的方法。分享给大家供大家参考,具体如下:

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背景图片

希望本文所述对大家Android程序设计有所帮助。

【Android自定义Button并设置不同背景图片的方法】相关文章:

android 分辨率适配的方法

Android中将一个图片切割成多个图片的实现方法

Android实现宫格图片连续滑动效果

Android自定义属性 format的深入解析

Android中 自定义数据绑定适配器BaseAdapter的方法

Android 设置应用全屏的两种解决方法

Android Intent启动别的应用实现方法

如何与Android实体设备的连接

用Android Location获取当前地理位置的方法

Android开发笔记之:复写按钮方法

精品推荐
分类导航