商城Sku实例

看到这个图大家可以延伸一个想法 ,第一步需要将View画出来,第二步就是将后台的数据进行解析然后开始循环从数据中来判断按钮是否可点,当然这时候我们还不清楚处逻辑是怎么进行判断

当然这一步逻辑我会放在第二步里面讲清楚   现在先开始第一步将view绘制出来  

一.  绘制布局

1.看到这个布局无非上面一个颜色TextView  下面是一个可以自动换行的ViewGrop我就不多讲了  直接上代码,无非就是在循环addView的时候计算子VIew的宽度和高度是否满足父View剩余的空间,如果满足直接在改行添加,不满足则换一行添加

public class SKUViewGroup extends ViewGroup {



    public SKUViewGroup(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    @Override
    protected ViewGroup.LayoutParams generateLayoutParams(
            ViewGroup.LayoutParams p)
    {
        return new MarginLayoutParams(p);
    }

    @Override
    public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs)
    {
        return new MarginLayoutParams(getContext(), attrs);
    }

    @Override
    protected ViewGroup.LayoutParams generateDefaultLayoutParams()
    {
        return new MarginLayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
    }

    /**
     * 负责设置子控件的测量模式和大小 根据所有子控件设置自己的宽和高
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 获得它的父容器为它设置的测量模式和大小
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);

        // 如果是warp_content情况下,记录宽和高
        int width = 0;
        int height = 0;
        /**
         * 记录每一行的宽度,width不断取最大宽度
         */
        int lineWidth = 0;
        /**
         * 每一行的高度,累加至height
         */
        int lineHeight = 0;

        int cCount = getChildCount();

        // 遍历每个子元素
        for (int i = 0; i < cCount; i++)
        {
            View child = getChildAt(i);
            // 测量每一个child的宽和高
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            // 得到child的布局管理器
            MarginLayoutParams lp = (MarginLayoutParams) child
                    .getLayoutParams();
            // 当前子空间实际占据的宽度
            int childWidth = child.getMeasuredWidth() + lp.leftMargin
                    + lp.rightMargin;
            // 当前子空间实际占据的高度
            int childHeight = child.getMeasuredHeight() + lp.topMargin
                    + lp.bottomMargin;
            /**
             * 如果加入当前child,则超出最大宽度,则的到目前最大宽度给width,类加height 然后开启新行
             */
            if (lineWidth + childWidth > sizeWidth)
            {
                width = Math.max(lineWidth, childWidth);// 取最大的
                lineWidth = childWidth; // 重新开启新行,开始记录
                // 叠加当前高度,
                height += lineHeight;
                // 开启记录下一行的高度
                lineHeight = childHeight;
            } else
            // 否则累加值lineWidth,lineHeight取最大高度
            {
                lineWidth += childWidth;
                lineHeight = Math.max(lineHeight, childHeight);
            }
            // 如果是最后一个,则将当前记录的最大宽度和当前lineWidth做比较
            if (i == cCount - 1)
            {
                width = Math.max(width, lineWidth);
                height += lineHeight;
            }

        }
        setMeasuredDimension((modeWidth == MeasureSpec.EXACTLY) ? sizeWidth
                : width, (modeHeight == MeasureSpec.EXACTLY) ? sizeHeight
                : height);

    }
    /**
     * 存储所有的View,按行记录
     */
    private List<List<View>> mAllViews = new ArrayList<>();
    /**
     * 记录每一行的最大高度
     */
    private List<Integer> mLineHeight = new ArrayList<>();
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b)
    {
        mAllViews.clear();
        mLineHeight.clear();

        int width = getWidth();

        int lineWidth = 0;
        int lineHeight = 0;
        // 存储每一行所有的childView
        List<View> lineViews = new ArrayList<>();
        int cCount = getChildCount();
        // 遍历所有的孩子
        for (int i = 0; i < cCount; i++)
        {
            View child = getChildAt(i);
            MarginLayoutParams lp = (MarginLayoutParams) child
                    .getLayoutParams();
            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();

            // 如果已经需要换行
            if (childWidth + lp.leftMargin + lp.rightMargin + lineWidth > width)
            {
                // 记录这一行所有的View以及最大高度
                mLineHeight.add(lineHeight);
                // 将当前行的childView保存,然后开启新的ArrayList保存下一行的childView
                mAllViews.add(lineViews);
                lineWidth = 0;// 重置行宽
                lineViews = new ArrayList<>();
            }
            /**
             * 如果不需要换行,则累加
             */
            lineWidth += childWidth + lp.leftMargin + lp.rightMargin;
            lineHeight = Math.max(lineHeight, childHeight + lp.topMargin
                    + lp.bottomMargin);
            lineViews.add(child);
        }
        // 记录最后一行
        mLineHeight.add(lineHeight);
        mAllViews.add(lineViews);

        int left = 0;
        int top = 0;
        // 得到总行数
        int lineNums = mAllViews.size();
        for (int i = 0; i < lineNums; i++)
        {
            // 每一行的所有的views
            lineViews = mAllViews.get(i);
            // 当前行的最大高度
            lineHeight = mLineHeight.get(i);

            // 遍历当前行所有的View
            for (int j = 0; j < lineViews.size(); j++)
            {
                View child = lineViews.get(j);
                if (child.getVisibility() == View.GONE)
                {
                    continue;
                }
                MarginLayoutParams lp = (MarginLayoutParams) child
                        .getLayoutParams();

                //计算childView的Marginleft,top,right,bottom
                int lc = left + lp.leftMargin;
                int tc = top + lp.topMargin;
                int rc =lc + child.getMeasuredWidth();
                int bc = tc + child.getMeasuredHeight();

                child.layout(lc, tc, rc, bc);

                left += child.getMeasuredWidth() + lp.rightMargin
                        + lp.leftMargin;
            }
            left = 0;
            top += lineHeight;
        }

    }

}

2.看到这里有多个相同的布局,而且行数不固定,有可能是多行  就使用了Recyclerview的Item模式   看一下Item布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView    //这个是TextView标题  例如:颜色
        android:id="@+id/tv_ItemName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dip"
        android:text="规格"
        android:gravity="center"
        android:textColor="#7f7f7f"
        android:focusable="false"
        android:textSize="12sp" />

    <com.yifeng.multiplesku.SKUViewGroup    //这个是自动换行的ViewGrop
        android:id="@+id/vg_skuItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:layout_marginTop="5dp"
        android:focusable="false"
        android:descendantFocusability="beforeDescendants" />
</LinearLayout>

布局这边已经完事了   下面是数据源  也就是从服务器获取的数据  我将它放在了 strings里面

<resources>
    <string name="app_name">MultipleSKU</string>
    <string name="jsonData">{
        "attributes": [
        {
            "tabID": 0,
            "tabName": "颜色",
            "attributesItem": [
                "白",
                "蓝",
                "黑"
            ]
        },
        {
            "tabID": 1,
            "tabName": "型号",
            "attributesItem": [
                "S",
                "X",
                "XL",
                "XXL"
            ]
        },
        {
            "tabID": 2,
            "tabName": "衣服",
            "attributesItem": [
                "羽绒服",
                "T恤",
                "棉毛衫"
            ]
        },
        {
            "tabID": 3,
            "tabName": "大小",
            "attributesItem": [
                "大",
                "中",
                "小"
            ]
        }
    ],
    "stockGoods": [
        {
            "goodsID": 1,
            "goodsInfo": [
                {
                    "tabID": 0,
                    "tabName": "颜色",
                    "tabValue": "白"
                },
                {
                    "tabID": 1,
                    "tabName": "型号",
                    "tabValue": "X"
                },
                {
                    "tabID": 2,
                    "tabName": "衣服",
                    "tabValue": "羽绒服"
                },
                {
                    "tabID": 3,
                    "tabName": "大小",
                    "tabValue": "中"
                }
            ]
        },
        {
            "goodsID": 2,
            "goodsInfo": [
                {
                    "tabID": 0,
                    "tabName": "颜色",
                    "tabValue": "黑"
                },
                {
                    "tabID": 1,
                    "tabName": "型号",
                    "tabValue": "XL"
                },
                {
                    "tabID": 2,
                    "tabName": "衣服",
                    "tabValue": "羽绒服"
                },
                {
                    "tabID": 3,
                    "tabName": "大小",
                    "tabValue": "大"
                }
            ]
        },
        {
            "goodsID": 3,
            "goodsInfo": [
                {
                    "tabID": 0,
                    "tabName": "颜色",
                    "tabValue": "白"
                },
                {
                    "tabID": 1,
                    "tabName": "型号",
                    "tabValue": "XXL"
                },
                {
                    "tabID": 2,
                    "tabName": "衣服",
                    "tabValue": "棉毛衫"
                },
                {
                    "tabID": 3,
                    "tabName": "大小",
                    "tabValue": "小"
                }
            ]
        },
        {
            "goodsID": 4,
            "goodsInfo": [
                {
                    "tabID": 0,
                    "tabName": "颜色",
                    "tabValue": "蓝"
                },
                {
                    "tabID": 1,
                    "tabName": "型号",
                    "tabValue": "S"
                },
                {
                    "tabID": 2,
                    "tabName": "衣服",
                    "tabValue": "棉毛衫"
                },
                {
                    "tabID": 3,
                    "tabName": "大小",
                    "tabValue": "小"
                }
            ]
        },
        {
            "goodsID": 5,
            "goodsInfo": [
                {
                    "tabID": 0,
                    "tabName": "颜色",
                    "tabValue": "黑"
                },
                {
                    "tabID": 1,
                    "tabName": "型号",
                    "tabValue": "XXL"
                },
                {
                    "tabID": 2,
                    "tabName": "衣服",
                    "tabValue": "T恤"
                },
                {
                    "tabID": 3,
                    "tabName": "大小",
                    "tabValue": "大"
                }
            ]
        }
    ]
}</string>
</resources>

接着看一下MainActivity代码

public class MainActivity extends AppCompatActivity implements SKUInterface {
    private TextView tv_title;//显示选中数据
    private RecyclerView rv_sku;
    private GoodsAttrsAdapter mAdapter;//recyclerview的适配器
    private GoodsAttrsBean dataBean;//数据源的Bean
    private Gson gson;//json解析器

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();//控件初始化和数据源读取
        install();//设置适配器和将数据传入适配器
    }
    private void init() {
        gson = new Gson();
        tv_title = (TextView) findViewById(R.id.tv_title);
        rv_sku = (RecyclerView) findViewById(R.id.rv_sku);
        dataBean = gson.fromJson(getResources().getString(R.string.jsonData), GoodsAttrsBean.class);
    }


    private void install() {
        mAdapter = new GoodsAttrsAdapter(getApplicationContext(), dataBean.getAttributes(), dataBean.getStockGoods());
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_sku.setLayoutManager(layoutManager);
        rv_sku.setFocusable(false);
        mAdapter.setSKUInterface(this);
        rv_sku.setAdapter(mAdapter);
    }


//选中事件  将选中的数据显示在View上
    @Override
    public void selectedAttribute(String[] attr) {
        String str = "";
        String ss = "";
        for (int i = 0; i < attr.length; i++) {
            str += " " + dataBean.getAttributes().get(i).getTabName() + ":";
            ss = TextUtils.isEmpty(attr[i]) ? "无" : attr[i];
            str += ss + " ";
        }
        tv_title.setText(str);
    }
//取消选中  将选中的数据显示在View上
    @Override
    public void uncheckAttribute(String[] attr) {
        String str = "";
        String ss = "";
        for (int i = 0; i < attr.length; i++) {
            str += " " + dataBean.getAttributes().get(i).getTabName() + ":";
            ss = TextUtils.isEmpty(attr[i]) ? "无" : attr[i];
            str += ss + " ";
        }
        tv_title.setText(str);
    }
}

二. 接下来就是核心部分  也就是逻辑部分  适配器

1.先将子View添加进childrenViews二维数组里面并且设置文字  【】【】 前面这个中括号代表行数  后面这个代表某一行的第几个 这样就将所有的子View添加进去了  这里是循环Bean里面attributes的大小

2.执行 initOptions(); 也就是把改成存的所有View全部设置成不可点击焦点消失

3.执行canClickOptions();从数据中找到符合要求的变为可点击焦点恢复

4.执行getSelected();找到选中的View设置成红色

canClickOptions()  这个方法就是一行一行的循环,再将数据stockGoodsList循环和已经选中的数据selectedValue  一个一个比较  ,比如选中是 白  S 羽绒服  大   和数据的第一个是白  X  羽绒服  大进行比较  选中的白色和数据的白比较相等那么就跳过本次循环继续下一个 选中S和数据的X比较不相等就直接结束循环,如果4个都相等那么就说明这一行的View有存在可选的  那么接下来将匹配的View进行点亮  将循环childrenViews【当前行数】里面的View得到Text和刚才满足数据进行比较设置成可以单击焦点恢复

public class GoodsAttrsAdapter extends BaseRecyclerAdapter<GoodsAttrsBean.AttributesBean> {

    private SKUInterface myInterface;

    private SimpleArrayMap<Integer, String> saveClick;

    private List<GoodsAttrsBean.StockGoodsBean> stockGoodsList;//商品数据集合
    private String[] selectedValue;   //选中的属性
    private TextView[][] childrenViews;    //二维 装所有属性

    private final int SELECTED = 0x100;
    private final int CANCEL = 0x101;

    public GoodsAttrsAdapter(Context ctx, List<GoodsAttrsBean.AttributesBean> list, List<GoodsAttrsBean.StockGoodsBean> stockGoodsList) {
        super(ctx, list);
        this.stockGoodsList = stockGoodsList;
        saveClick = new SimpleArrayMap<>();
        childrenViews = new TextView[list.size()][0];
        selectedValue = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            selectedValue[i] = "";
        }
    }

    public void setSKUInterface(SKUInterface myInterface) {
        this.myInterface = myInterface;
    }

    @Override
    public int getItemLayoutId(int viewType) {
        return R.layout.item_skuattrs;
    }

    @Override
    public void bindData(RecyclerViewHolder holder, int position, GoodsAttrsBean.AttributesBean item) {
        TextView tv_ItemName = holder.getTextView(R.id.tv_ItemName);
        SKUViewGroup vg_skuItem = (SKUViewGroup) holder.getView(R.id.vg_skuItem);
        tv_ItemName.setText(item.getTabName());
        List<String> childrens = item.getAttributesItem();
        int childrenSize = childrens.size();
        TextView[] textViews = new TextView[childrenSize];
        for (int i = 0; i < childrenSize; i++) {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(5, 5, 5, 0);
            TextView textView = new TextView(mContext);
            textView.setGravity(Gravity.CENTER);
            textView.setPadding(15, 5, 15, 5);
            textView.setLayoutParams(params);
            textView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.saddlebrown));
            textView.setText(childrens.get(i));
            textView.setTextColor(ContextCompat.getColor(mContext, R.color.white));
            textViews[i] = textView;
            vg_skuItem.addView(textViews[i]);
        }
        childrenViews[position] = textViews;
        initOptions();
        canClickOptions();
        getSelected();
    }

    private int focusPositionG, focusPositionC;

    private class MyOnClickListener implements View.OnClickListener {
        //点击操作 选中SELECTED   取消CANCEL
        private int operation;

        private int positionG;

        private int positionC;

        public MyOnClickListener(int operation, int positionG, int positionC) {
            this.operation = operation;
            this.positionG = positionG;
            this.positionC = positionC;
        }

        @Override
        public void onClick(View v) {
            focusPositionG = positionG;
            focusPositionC = positionC;
            String value = childrenViews[positionG][positionC].getText().toString();
            switch (operation) {
                case SELECTED:
                    saveClick.put(positionG, positionC + "");
                    selectedValue[positionG] = value;
                    myInterface.selectedAttribute(selectedValue);
                    break;
                case CANCEL:
                    saveClick.put(positionG, "");
                    for (int l = 0; l < selectedValue.length; l++) {
                        if (selectedValue[l].equals(value)) {
                            selectedValue[l] = "";
                            break;
                        }
                    }
                    myInterface.uncheckAttribute(selectedValue);
                    break;
            }
            initOptions();
            canClickOptions();
            getSelected();
        }
    }


    class MyOnFocusChangeListener implements View.OnFocusChangeListener {

        private int positionG;

        private int positionC;


        public MyOnFocusChangeListener(int positionG, int positionC) {
            this.positionG = positionG;
            this.positionC = positionC;
        }

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            String clickpositionC = saveClick.get(positionG);
            if (hasFocus) {
                v.setBackgroundColor(ContextCompat.getColor(mContext, R.color.pink));
                if (TextUtils.isEmpty(clickpositionC)) {
                    ((TextView) v).setTextColor(ContextCompat.getColor(mContext, R.color.dodgerblue));
                } else if (clickpositionC.equals(positionC + "")) {

                } else {
                    ((TextView) v).setTextColor(ContextCompat.getColor(mContext, R.color.dodgerblue));
                }
            } else {
                v.setBackgroundColor(ContextCompat.getColor(mContext, R.color.saddlebrown));
                if (TextUtils.isEmpty(clickpositionC)) {
                    ((TextView) v).setTextColor(ContextCompat.getColor(mContext, R.color.white));
                } else if (clickpositionC.equals(positionC + "")) {

                } else {
                    ((TextView) v).setTextColor(ContextCompat.getColor(mContext, R.color.white));
                }
            }
        }

    }

    /**
     * 初始化选项(不可点击,焦点消失)
     */
    private void initOptions() {
        for (int y = 0; y < childrenViews.length; y++) {
            for (int z = 0; z < childrenViews[y].length; z++) {//循环所有属性
                TextView textView = childrenViews[y][z];
                textView.setEnabled(false);
                textView.setFocusable(false);
                textView.setTextColor(ContextCompat.getColor(mContext, R.color.gray));//变灰
            }
        }
    }

    /**
     * 找到符合条件的选项变为可选
     */
    private void canClickOptions() {
        for (int i = 0; i < childrenViews.length; i++) {//这是View每一行
            for (int j = 0; j < stockGoodsList.size(); j++) {//将数据库的数据全部遍历  如果满足选中的数据  那么将view设置成可见状态
                boolean filter = true;
                List<GoodsAttrsBean.StockGoodsBean.GoodsInfoBean> goodsInfo = stockGoodsList.get(j).getGoodsInfo();//每一个数据的详细信息
                for (int k = 0; k < selectedValue.length; k++) {//判断选中的数据在数据库中是否满足  进行数据的比对 0-0 1-1 2-2
                    if (i == k || TextUtils.isEmpty(selectedValue[k])) {
                        continue;
                    }
                    if (!selectedValue[k].equals(goodsInfo.get(k).getTabValue())) {//只要有一个不满足就不设置成可选状态
                        filter = false;
                        break;
                    }
                }
                if (filter) {//进行数据匹配
                    for (int n = 0; n < childrenViews[i].length; n++) {
                        TextView textView = childrenViews[i][n];//拿到所有属性TextView
                        String name = textView.getText().toString();

                        if (goodsInfo.get(i).getTabValue().equals(name)&&!textView.isEnabled()) {//将满足的属性和View进行匹配   找到view就设置成可选状态
                            textView.setEnabled(true);//符合就变成可点击
                            textView.setFocusable(true); //设置可以获取焦点
                            //不要让焦点乱跑
                            if (focusPositionG == i && focusPositionC == n) {
                                textView.setTextColor(ContextCompat.getColor(mContext, R.color.dodgerblue));
                                textView.requestFocus();
                            } else {
                                textView.setTextColor(ContextCompat.getColor(mContext, R.color.white));
                            }
                            textView.setOnClickListener(new MyOnClickListener(SELECTED, i, n) {
                            });
                            textView.setOnFocusChangeListener(new MyOnFocusChangeListener(i, n) {
                            });
                        }
                    }
                }
            }
        }
    }

    /**
     * 找到已经选中的选项,让其变红
     */
    private void getSelected() {
        for (int i = 0; i < childrenViews.length; i++) {
            for (int j = 0; j < childrenViews[i].length; j++) {//拿到每行属性Item
                TextView textView = childrenViews[i][j];//拿到所有属性TextView
                String value = textView.getText().toString();
                for (int m = 0; m < selectedValue.length; m++) {
                    if (selectedValue[m].equals(value)) {
                        textView.setTextColor(ContextCompat.getColor(mContext, R.color.red));
                        textView.setOnClickListener(new MyOnClickListener(CANCEL, i, j) {
                        });
                    }
                }
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值