转载请注明出处

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

更多相关文章

  1. Android 5.0新控件 AppBarLayout | 嵌套布局 介绍及使用详情
  2. RecyclerView Android RecyclerView 使用完全解析 体验艺术般的
  3. android 调用android系统的对话框控件
  4. 初识Android之(一)-自定义标题栏控件
  5. 基本控件学习二 (多选框)
  6. 控件_ProgressBar

随机推荐

  1. 谈谈Android个人开发者的现状
  2. Android中“分享”功能的实现
  3. 一场关于Android的争论
  4. Android(安卓)连接WIF获取的信息剖析
  5. Android虚拟平台的编译和整合
  6. Android(安卓)性能优化 内存优化 How And
  7. Android中“分享”功能的实现
  8. Android的init过程详解(一)
  9. Android百度地图之位置定位和附近查找代
  10. Android(安卓)Socket 发送广播包的那些坑