`
xiaoheliushuiya
  • 浏览: 405158 次
文章分类
社区版块
存档分类
最新评论

简单的自定义View的实现

 
阅读更多

项目中要用到一个记录订单数量的控件,要求实现的效果是每次点击这个控件,里面的值就会自动加一,直至加大最大之后又重新从一开始加。之前一直是使用默认的TextView来实现的,但是考虑到项目中又多个地方要用到这个控件,所以决定把它自定义一下。


(控件的截图)

1、以前的实现的方法

int count = Integer.parseInt(amount.getText().toString());
			amount.setText(String.valueOf(count % 5 + 1));

2、自定义View的方法

首先定义一个View,叫AmountView,继承自TextView。具体代码如下:

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.TextView;

/**
 * 自定义UI控件,记录菜的份数
 * 
 * @school University of South China
 * @date 2014.01
 */
public class AmountView extends TextView {
	/**
	 * 最大的份数
	 */
	private int mMaxAmount = 5;
	/**
	 * 当前显示的份数
	 */
	private int mAmount = 1;

	public AmountView(Context context) {
		super(context);
		setText(mAmount + "");
	}

	public AmountView(Context context, AttributeSet attrs) {
		super(context, attrs);
		setText(mAmount + "");
	}

	public AmountView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		setText(mAmount + "");
	}

	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_UP) {
			mAmount = mAmount % mMaxAmount + 1;
			setText(mAmount + "");
			System.out.println("AmoutView onTouchEvent");
		}
		return super.onTouchEvent(event);
	}

	
	public void setMaxAmount(int maxAmount) {
		mMaxAmount = maxAmount;
	}

	public void setAmount(int amount) {
		this.mAmount = amount;
		setText("" + mAmount);
	}

}

注意的几个地方:

(1)必须要实现默认的三个构造方法。

(2)setText方法的参数是Charsequece,不能传int型参数,所以mAmount 后面加双引号。

(3)在onTouchEvent()方法中处理点击事件


然后在在布局文件中用完整的包名申明该控件即可使用了。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics