发布于 2016-05-20 03:57:54 | 273 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的精品教程,程序狗速度看过来!

Android移动端操作系统

Android是一种基于Linux的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由Google公司和开放手机联盟领导及开发。尚未有统一中文名称,中国大陆地区较多人使用“安卓”或“安致”。


这篇文章主要介绍了Android自定义Button并设置不同背景图片的方法,涉及Android自定义控件的功能实现与布局相关技巧,需要的朋友可以参考下

本文实例讲述了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背景图片



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务