java 购物车 - 增加减少商品数量 - 控件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 购物车 - 增加减少商品数量 - 控件相关的知识,希望对你有一定的参考价值。
/**
* 加和减数量的控件
* Created by 洪少鹏 on 2017/10/16.
*/
public class AddAndSunTextView extends android.support.v7.widget.AppCompatTextView {
Drawable mADD, mSUB, mSUB_UNABLE;
public AddAndSunTextView(Context context) {
super(context);
}
public AddAndSunTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();//初始化
}
/**
* 初始化,设置初始值
*/
private void init() {
//getCompoundDrawables获取到的是textview的 android:drawableLeft="@drawable/cart_minus"
//android:drawableRight="@drawable/cart_add" 这里面的图标。
mSUB = getCompoundDrawables()[0];
mADD = getCompoundDrawables()[2];
mSUB_UNABLE = getResources().getDrawable(R.drawable.cart_minus);
this.setText(1 + "");//设置初始值为0
}
/**
* 获取点击时X值,判断其所在位置来虚拟点击事件
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
int num;
float X, add_left, add_right, sub_left, sub_right;
X = event.getX();
add_right = getTotalPaddingLeft();
add_left = getPaddingLeft();
sub_right = getWidth() - getPaddingRight();
sub_left = getWidth() - getTotalPaddingRight();
if (TextUtils.isEmpty(this.getText().toString())) {
num = 1;
} else {
num = Integer.parseInt(getText().toString());
}
if (X > add_left && X < add_right) {
//如果为1,模拟不响应点击事件
if (num == 1) {
this.setText(1 + "");
} else {
num--;
// num = setCheckadle(num);//检验当前输入框数字,若为1则设置减号按钮不可见;
this.setText(num + "");
}
} else if (X > sub_left && X < sub_right) {
num++;
num = setCheckadle(num);//检验当前输入框数字,若不为1则设置减号按钮可见
this.setText(num + "");
}
return super.onTouchEvent(event);
}
/**
* 判断num值,对加减号进行设置:若num = 1,减号不可用;若num = 99,加号不可用(限制num在0~99区间)
*
* @param num
* @return
*/
private int setCheckadle(int num) {
if (num == 1) {
setCompoundDrawables(mSUB_UNABLE, getCompoundDrawables()[1], getCompoundDrawables()[2], getCompoundDrawables()[3]);
} else {
setCompoundDrawables(mSUB, getCompoundDrawables()[1], getCompoundDrawables()[2], getCompoundDrawables()[3]);
}
if (num == 99) {
setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], null, getCompoundDrawables()[3]);
} else {
setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], mADD, getCompoundDrawables()[3]);
}
return num;
}
/**
* 获取此时计数器的值
*
* @return
*/
public String getNum() {
return this.getText().toString();
}
}
以上是关于java 购物车 - 增加减少商品数量 - 控件的主要内容,如果未能解决你的问题,请参考以下文章