商城购物车加减控件的简单封装

5,048 阅读8分钟

我们都知道,购物车是做商城项目必不可少的一个环节,购物车中的加减控件就是商城中的重中之重,最近项目中也用到了加减控件,但是使用起来样式不能随便更改,决定简单封装一下,以后用到的时候就不那么麻烦了,几行代码就搞定。本文主要是对封装的过程进行一下整理。

1. 先看下效果图

效果图:

AddSubUtils.gif
AddSubUtils.gif

Github地址:AddSubUtils

同步csdn和简书:
csdn地址:商城购物车加减控件的简单封装
简书地址:商城购物车加减控件的简单封装

2. 需求分析

  • 可以手动输入,也可以加减控件微调。
  • 加入购买的最大值(实际开发中可能有)
  • 加入商品的库存(实际开发中可能有)
  • 加入步长,当数大的时候不可能一直按1去加
  • 加入购买的最小值
  • 加入输入框可以在左中右(实际开发中可能有)
  • 可以自由指定控件的样式

这里涵盖了大部分的加减控件的需求,对于我们来说,我们只需要简单的调用就ok了,所以接下来会把逻辑处理部分封装在一个类中,并且自定义属性,可以让我们随时更改样式。

3. 实现思路

简单理一下思路,第一点如果支持手动输入,TextView是满足不了需求的,这里使用EditText,第二点,咱们把关于样式的放在自定义属性中,在xml代码中去控制,至于最大值、库存、步长、最小值等放在代码中调用的时候赋值,默认最大值和库存都为int的最大值,即Integer.MAX_VALUE,步长、当前值和最小值为1。

3.1 自定义加减控件的布局和样式

布局:add_sub_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:divider="@drawable/divider_horizontal"
    android:background="@drawable/addsubutils_add_sub_bg"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/ic_minus"
        android:layout_width="@dimen/addsubutils_btn_width"
        android:layout_height="match_parent"
        android:background="@drawable/addsubutils_left_selector"
        android:clickable="true"
        android:padding="@dimen/addsubutils_btn_padding"
        android:scaleType="centerInside"
        android:src="@drawable/addsubutils_ic_minus" />

    <EditText
        android:id="@+id/et_input"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@null"
        android:cursorVisible="true"
        android:digits="0123456789"
        android:gravity="center"
        android:singleLine="true"
        android:inputType="number"
        android:minWidth="@dimen/addsubutils_et_minwidth"
        android:text="1"
        android:textColor="@color/addsubutils_text"
        android:textCursorDrawable="@null"
        android:textSize="@dimen/addsubutils_textsize"/>

    <ImageView
        android:id="@+id/ic_plus"
        android:layout_width="@dimen/addsubutils_btn_width"
        android:layout_height="match_parent"
        android:background="@drawable/addsubutils_right_selector"
        android:clickable="true"
        android:padding="@dimen/addsubutils_btn_padding"
        android:scaleType="centerInside"
        android:src="@drawable/addsubutils_ic_plus" />
</LinearLayout>

这里非常简单,就是一个水平的Linear包裹了两个ImageView和一个EditText,这里用到几种的样式

整体背景样式:addsubutils_add_sub_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke
        android:width="1dp"
        android:color="@color/divider"/>
    <corners android:radius="3dp"/>
</shape>

左边按钮默认背景样式:addsubutils_left_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:enterFadeDuration="200" android:exitFadeDuration="200">
    <item android:state_pressed="true" >
        <shape>
            <stroke android:color="@color/divider"
                android:width="1dp"/>
            <solid android:color="@color/divider"/>
            <corners android:topLeftRadius="3dp"
                android:bottomLeftRadius="3dp"/>
        </shape>
    </item>
    <item android:state_pressed="false" >
        <shape>
            <stroke android:color="@color/divider"
                android:width="1dp"/>
            <corners android:topLeftRadius="3dp"
                android:bottomLeftRadius="3dp"/>
        </shape>
    </item>
</selector>

右边按钮默认背景样式:addsubutils_right_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:enterFadeDuration="200" android:exitFadeDuration="200">
    <item android:state_pressed="true" >
        <shape>
            <stroke android:color="@color/divider"
                android:width="1dp"/>
            <solid android:color="@color/divider"/>
            <corners android:topRightRadius="3dp"
                android:bottomRightRadius="3dp"/>
        </shape>
    </item>
    <item android:state_pressed="false" >
        <shape>
            <stroke android:color="@color/divider"
                android:width="1dp"/>
            <corners android:topRightRadius="3dp"
                android:bottomRightRadius="3dp"/>
        </shape>
    </item>
</selector>

dimens中字体大小和边距

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="addsubutils_btn_width" >30dp</dimen>
    <dimen name="addsubutils_btn_padding">10dp</dimen>
    <dimen name="addsubutils_textsize" >15sp</dimen>
    <dimen name="addsubutils_et_minwidth" >65dp</dimen>
</resources>

分割线divider_horizontal的样式

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size
        android:width="1dp"/>
    <solid android:color="@color/divider"/>
</shape>

用到的图片:

addsubutils_ic_plus
addsubutils_ic_plus
addsubutils_ic_minus
addsubutils_ic_minus

3.2 自定义AddSubUtils继承LinearLayout

/**
 * Created by 贾梦飞 on 2017/8/10 10:55.
 * QQ:821176301
 * 微信:j821176301
 * desc:购物车功能的增加和加减
 */
public class AddSubUtils extends LinearLayout {

    private EditText etInput;
    private ImageView icPlus;
    private ImageView icMinus;

    public AddSubUtils(Context context) {
        this(context, null);
    }

    public AddSubUtils(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AddSubUtils(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void init(Context context, AttributeSet attrs, int defStyleAttr) { 
            // 把布局和当前类形成整体
            LayoutInflater.from(context).inflate(R.layout.add_sub_layout, this);
            icPlus = (ImageView) findViewById(R.id.ic_plus);
            icMinus = (ImageView) findViewById(R.id.ic_minus);
            etInput = (EditText) findViewById(R.id.et_input);
    }
}

3.3 在init()方法中加入自定义属性和样式


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        //得到属性
        if (attrs != null) {
            TypedArray typeArray = getContext().obtainStyledAttributes(attrs, R.styleable.AddSubUtils);
            boolean editable = typeArray.getBoolean(R.styleable.AddSubUtils_editable, true);
            String location = typeArray.getString(R.styleable.AddSubUtils_location);
            // 左右两面的宽度
            int ImageWidth = typeArray.getDimensionPixelSize(R.styleable.AddSubUtils_ImageWidth, -1);
            // 中间内容框的宽度
            int contentWidth = typeArray.getDimensionPixelSize(R.styleable.AddSubUtils_contentWidth, -1);
            // 中间字体的大小
            int contentTextSize = typeArray.getDimensionPixelSize(R.styleable.AddSubUtils_contentTextSize, -1);
            // 中间字体的颜色
            int contentTextColor = typeArray.getColor(R.styleable.AddSubUtils_contentTextColor, 0xff000000);
            // 整个控件的background
            Drawable background = typeArray.getDrawable(R.styleable.AddSubUtils_all_background);
            // 左面控件的背景
            Drawable leftBackground = typeArray.getDrawable(R.styleable.AddSubUtils_leftBackground);
            // 右面控件的背景
            Drawable rightBackground = typeArray.getDrawable(R.styleable.AddSubUtils_rightBackground);
            // 中间控件的背景
            Drawable contentBackground = typeArray.getDrawable(R.styleable.AddSubUtils_contentBackground);
            // 左面控件的资源
            Drawable leftResources = typeArray.getDrawable(R.styleable.AddSubUtils_leftResources);
            // 右面控件的资源
            Drawable rightResources = typeArray.getDrawable(R.styleable.AddSubUtils_rightResources);
            // 资源回收
            typeArray.recycle();

            // 如果是start就说明输入框在左边,如果是end说明输入框在右面,否则默认是在中间
            if("start".equals(location)) {
                //把布局和当前类形成整体
                LayoutInflater.from(context).inflate(R.layout.add_sub_start_layout, this);
            }else if("end".equals(location)) {
                //把布局和当前类形成整体
                LayoutInflater.from(context).inflate(R.layout.add_sub_end_layout, this);
            }else {
                //把布局和当前类形成整体
                LayoutInflater.from(context).inflate(R.layout.add_sub_layout, this);
            }

            icPlus = (ImageView) findViewById(R.id.ic_plus);
            icMinus = (ImageView) findViewById(R.id.ic_minus);
            etInput = (EditText) findViewById(R.id.et_input);

            // 设置EditText是否可点击
            setEditable(editable);
            etInput.setTextColor(contentTextColor);

            // 设置两边按钮的宽度
            if (ImageWidth > 0) {
                LayoutParams textParams = new LayoutParams(ImageWidth, LayoutParams.MATCH_PARENT);
                icPlus.setLayoutParams(textParams);
                icMinus.setLayoutParams(textParams);
            }

            // 设置中间输入框的宽度
            if (contentWidth > 0) {
                LayoutParams textParams = new LayoutParams(contentWidth, LayoutParams.MATCH_PARENT);
                etInput.setLayoutParams(textParams);
            }
            if (contentTextColor > 0) {
                etInput.setTextSize(contentTextColor);
            }
            if(contentTextSize > 0) {
                etInput.setTextSize(contentTextSize);
            }
            if (background != null) {
                setBackgroundDrawable(background);
            } else {
                setBackgroundResource(R.drawable.addsubutils_add_sub_bg);
            }

            if (contentBackground != null) {
                etInput.setBackground(contentBackground);
            }

            if(leftBackground != null) {
                icMinus.setBackground(leftBackground);
            }

            if (rightBackground != null){
                icPlus.setBackground(rightBackground);
            }
            if (leftResources != null){
                icMinus.setImageDrawable(leftResources);
            }
            if(rightResources != null) {
                icPlus.setImageDrawable(rightResources);
            }
        }
    }

    private void setEditable(boolean editable) {
        if (editable) {
            etInput.setFocusable(true);
            etInput.setKeyListener(new DigitsKeyListener());
        } else {
            etInput.setFocusable(false);
            etInput.setKeyListener(null);
        }
    }

首先使用TypedArray得到自定义属性值,然后传给对应的控件,这里注释写的很详细。

3.4 加入点击事件和EditText输入框的监听

在init()方法中:

            icPlus.setOnClickListener(this);
            icMinus.setOnClickListener(this);
            etInput.addTextChangedListener(this);

AddSubUtils类实现View.OnClickListener, TextWatcher这两个接口,并重写onClick()和其他的方法

public class AddSubUtils extends LinearLayout implements View.OnClickListener, TextWatcher {
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ic_plus) {
            // 加
            if (inputValue < Math.min(mBuyMax, inventory)) {
                inputValue += mStep;
                //正常添加
                etInput.setText("" + inputValue);
            } else if (inventory < mBuyMax) {
                //库存不足
                warningForInventory();
            } else {
                //超过最大购买数
                warningForBuyMax();
            }
        } else if (id == R.id.ic_minus) {
            // 减
            if (inputValue > mBuyMin) {
                inputValue -= mStep;
                etInput.setText(inputValue + "");
            } else {
                // 低于最小购买数
                warningForBuyMin();
            }
        } else if (id == R.id.et_input) {
            // 输入框
            etInput.setSelection(etInput.getText().toString().length());
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        onNumberInput();
    }

    /**
     * 监听输入的数据变化
     */
    private void onNumberInput() {
        //当前数量
        int count = getNumber();
        if (count < mBuyMin) {
            //手动输入
            etInput.setText(mBuyMin + "");
            return;
        }
        int limit = Math.min(mBuyMax, inventory);
        if (count > limit) {
            if (inventory < mBuyMax) {
                //库存不足
                warningForInventory();
            } else {
                //超过最大购买数
                warningForBuyMax();
            }
        }else{
           inputValue = count;
        }
    }
}

这里具体逻辑大家一看就明白,我就不再重复了

3.5 定义警告的接口

    public interface OnWarnListener {
        // 不能超过库存
        void onWarningForInventory(int inventory);
        // 不能超过购买最大数
        void onWarningForBuyMax(int max);
        // 不能低于最小购买数
        void onWarningForBuyMin(int min);
    }

3.6 通过链式调用,设置需要的数据

    public AddSubUtils setCurrentNumber(int currentNumber) {
        if (currentNumber < mBuyMin){
            inputValue = mBuyMin;
        } else {
            inputValue = Math.min(Math.min(mBuyMax, inventory), currentNumber);
        }
        etInput.setText(inputValue + "");
        return this;
    }

    public int getInventory() {
        return inventory;
    }

    public AddSubUtils setInventory(int inventory) {
        this.inventory = inventory;
        return this;
    }

    public int getBuyMax() {
        return mBuyMax;
    }

    public AddSubUtils setBuyMax(int buyMax) {
        mBuyMax = buyMax;
        return this;
    }
    public AddSubUtils setBuyMin(int buyMin) {
        mBuyMin = buyMin;
        return this;
    }

    public AddSubUtils setOnWarnListener(OnWarnListener onWarnListener) {
        mOnWarnListener = onWarnListener;
        return this;
    }
    public int getStep() {
        return mStep;
    }

    public AddSubUtils setStep(int step) {
        mStep = step;
        return this;
    }

到这里你已经封装完成了,具体demo可以去Github下载

4. 如何使用

step 1. 在app的build.gradle中添加依赖

dependencies {
 compile 'com.mengfei:AddSubUtils:1.0.0'
}

或者下载源码包,链接:github.com/Jmengfei/Ad… ,并且在build.gradle中添加:

dependencies {
 compile project(':addsubutils')
}

step 2. 在xml代码中使用

    <com.mengfei.AddSubUtils
        android:id="@+id/add_sub"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

你也可以自定义样式:

 <com.mengfei.AddSubUtils
        android:id="@+id/add_sub_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        jmf:editable="true"
        jmf:ImageWidth="60dp"
        jmf:contentTextColor="@color/colorText"
        jmf:contentWidth="120dp"
        jmf:contentTextSize="16sp"
        jmf:contentBackground="@color/material_teal_200"
        jmf:leftBackground="@drawable/left_selector"
        jmf:rightBackground="@drawable/right_selector"
        jmf:leftResources="@drawable/minus"
        jmf:rightResources="@drawable/plus"/>

step3. 在Activity或者Fragment中配置AddSubUtils

        AddSubUtils addSubUtils = (AddSubUtils) findViewById(R.id.add_sub);
        addSubUtils.setBuyMax(30)       // 最大购买数,默认为int的最大值
                .setInventory(50)       // 库存,默认为int的最大值
                .setCurrentNumber(5)    // 设置当前数,默认为1
                .setStep(5)             // 步长,默认为1
                .setBuyMin(2)           // 购买的最小值,默认为1
                .setOnWarnListener(new AddSubUtils.OnWarnListener() {
                    @Override
                    public void onWarningForInventory(int inventory) {
                        Toast.makeText(MainActivity.this, "当前库存:" + inventory, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onWarningForBuyMax(int max) {
                        Toast.makeText(MainActivity.this, "超过最大购买数:" + max, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onWarningForBuyMin(int min) {
                        Toast.makeText(MainActivity.this, "低于最小购买数:" + min, Toast.LENGTH_SHORT).show();
                    }
                });

这里你只需要传入你关心的值即可。

5.支持 Attributes属性(addsubutils布局文件中调用)

Attributes forma describe
editable boolean 是否可以手动输入
location string 输入框的位置(在左边还是右边),默认中间
ImageWidth dimension 左右2边+-按钮的宽度
contentWidth dimension 中间EditText的宽度
contentTextSize dimension 中间EditText的字体大小
contentTextColor color 中间字体的颜色
all_background color/reference 整个控件的background
leftBackground color/reference 左面控件的背景
rightBackground color/reference 右面控件的背景
contentBackground color/reference 中间控件的背景
leftResources color/reference 左面控件的资源
rightResources color/reference 右面控件的资源

以上就是对商城购物车加减控件的一些介绍和一个简单的封装。需要源码的朋友,请看 Github地址:AddSubUtils,如果觉得对你有用的话,欢迎star。

客官别走
在v1.5.0版本中解决了在ListView中由于item的复用导致数据错乱的问题:
地址: 商城购物车加减控件的简单封装(续),解决ListView中数据错乱的问题 如果你觉得对你有用的话,不妨留下你的足迹。