第二周练习

MainActivity页面

public class MainActivity extends AppCompatActivity {
    @BindView(R.id.main_button01)
    Button mainButton01;
    @BindView(R.id.main_button02)
    Button mainButton02;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);


    }

    @OnClick({R.id.main_button01, R.id.main_button02})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.main_button01:
                startActivity(new Intent(this, TuYi.class));
                break;
            case R.id.main_button02:
                startActivity(new Intent(this, TuEr.class));
                break;
        }
    }

}

MyAdapter页面

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    private Context context;
    private List<SousuoBean.DataBean> list;
    OnItemClickListener mOnItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.mOnItemClickListener = onItemClickListener;
    }

    public MyAdapter(Context context, List<SousuoBean.DataBean> list) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ViewHolder holder;
        View view = View.inflate(context, R.layout.sousuo_recy_item, null);
        holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
        holder.tv1.setText(list.get(position).getSubhead());
        holder.tv2.setText(list.get(position).getTitle());
        String icon = (String) list.get(position).getImages();
        if (icon.indexOf("|") != -1) {
            String result = icon.substring(0, icon.indexOf("|"));
            //加载图片  url=result
            holder.touXiang.setImageURI(result);
        } else {
            //加载图片  url=iamges
            holder.touXiang.setImageURI(icon);
        }
        if (mOnItemClickListener != null) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOnItemClickListener.onClick(position);
                }
            });
            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    mOnItemClickListener.onLongClick(position);
                    return false;
                }
            });
        }

    }


    @Override
    public int getItemCount() {
        return list.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        SimpleDraweeView touXiang;
        TextView tv1;
        TextView tv2;


        public ViewHolder(View itemView) {
            super(itemView);
            touXiang = itemView.findViewById(R.id.item_simple);
            tv1 = itemView.findViewById(R.id.item_textView);
            tv2 = itemView.findViewById(R.id.item_textView2);

        }
    }
}
FlowLayout页面

public class FlowLayout extends ViewGroup {

    public FlowLayout(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

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

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

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {

        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);

        // 如果是warp_content情况下,记录宽和高
        int width = 0;
        int height = 0;

        // 记录每一行的宽度与高度
        int lineWidth = 0;
        int lineHeight = 0;

        // 得到内部元素的个数
        int cCount = getChildCount();

        for (int i = 0; i < cCount; i++)
        {
            // 通过索引拿到每一个子view
            View child = getChildAt(i);
            // 测量子View的宽和高,系统提供的measureChild
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            // 得到LayoutParams
            MarginLayoutParams lp = (MarginLayoutParams) child
                    .getLayoutParams();

            // View占据的宽度
            int childWidth = child.getMeasuredWidth() + lp.leftMargin
                    + lp.rightMargin;
            // View占据的高度
            int childHeight = child.getMeasuredHeight() + lp.topMargin
                    + lp.bottomMargin;

            // 换行 判断 当前的宽度大于 开辟新行
            if (lineWidth + childWidth > sizeWidth - getPaddingLeft() - getPaddingRight())
            {
                // 对比得到最大的宽度
                width = Math.max(width, lineWidth);
                // 重置lineWidth
                lineWidth = childWidth;
                // 记录行高
                height += lineHeight;
                lineHeight = childHeight;
            }
            else
            // 未换行
            {
                // 叠加行宽
                lineWidth += childWidth;
                // 得到当前行最大的高度
                lineHeight = Math.max(lineHeight, childHeight);
            }
            // 特殊情况,最后一个控件
            if (i == cCount - 1)
            {
                width = Math.max(lineWidth, width);
                height += lineHeight;
            }
        }
        setMeasuredDimension(
                modeWidth == MeasureSpec.EXACTLY ? sizeWidth : width + getPaddingLeft() + getPaddingRight(),
                modeHeight == MeasureSpec.EXACTLY ? sizeHeight : height + getPaddingTop() + getPaddingBottom()//
        );

    }

    /**
     * 存储所有的View
     */
    private List<List<View>>    mAllViews   = new ArrayList<List<View>>();
    /**
     * 每一行的高度
     */
    private List<Integer> mLineHeight = new ArrayList<Integer>();

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b)
    {
        mAllViews.clear();
        mLineHeight.clear();

        // 当前ViewGroup的宽度
        int width = getWidth();

        int lineWidth = 0;
        int lineHeight = 0;

        // 存放每一行的子view
        List<View> lineViews = new ArrayList<View>();

        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 + lineWidth + lp.leftMargin + lp.rightMargin > width - getPaddingLeft() - getPaddingRight())
            {
                // 记录LineHeight
                mLineHeight.add(lineHeight);
                // 记录当前行的Views
                mAllViews.add(lineViews);

                // 重置我们的行宽和行高
                lineWidth = 0;
                lineHeight = childHeight + lp.topMargin + lp.bottomMargin;
                // 重置我们的View集合
                lineViews = new ArrayList<View>();
            }
            lineWidth += childWidth + lp.leftMargin + lp.rightMargin;
            lineHeight = Math.max(lineHeight, childHeight + lp.topMargin
                    + lp.bottomMargin);
            lineViews.add(child);

        }// for end
        // 处理最后一行
        mLineHeight.add(lineHeight);
        mAllViews.add(lineViews);

        // 设置子View的位置

        int left = getPaddingLeft();
        int top = getPaddingTop();

        // 行数
        int lineNum = mAllViews.size();

        for (int i = 0; i < lineNum; i++)
        {
            // 当前行的所有的View
            lineViews = mAllViews.get(i);
            lineHeight = mLineHeight.get(i);

            for (int j = 0; j < lineViews.size(); j++)
            {
                View    child = lineViews.get(j);
                // 判断child的状态
                if (child.getVisibility() == View.GONE)
                {
                    continue;
                }

                MarginLayoutParams lp = (MarginLayoutParams) child
                        .getLayoutParams();

                int lc = left + lp.leftMargin;
                int tc = top + lp.topMargin;
                int rc = lc + child.getMeasuredWidth();
                int bc = tc + child.getMeasuredHeight();

                // 为子View进行布局
                child.layout(lc, tc, rc, bc);

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

    }

    /**
     * 与当前ViewGroup对应的LayoutParams
     */
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs)
    {
        return new MarginLayoutParams(getContext(), attrs);
    }

}
OnItemClickListener接口

public interface OnItemClickListener {
    void onClick(int position);
    void onLongClick(int position);
}
 
 
SousuoActivity页面

public class SousuoActivity extends AppCompatActivity implements SousuoView {
    int page = 1;
    @BindView(R.id.recy)
    RecyclerView mRecy;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private SousuoPresenter sousuoPresenter;
    private String keywords;
    private List<SousuoBean.DataBean> data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sousuo);
        ButterKnife.bind(this);
        keywords = getIntent().getStringExtra("keywords");
        Log.d("SousuoActivity", keywords);

        sousuoPresenter = new SousuoPresenter();
        sousuoPresenter.attachView(this);
        sousuoPresenter.getData(Api.DUANZI_API, keywords, page);

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                page = page + 1;
                Log.d("SousuoActivity", "page:" + page);
                sousuoPresenter.getData(Api.DUANZI_API, keywords, page);
                refreshLayout.finishLoadMore(2000);
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                page = 1;
                sousuoPresenter.getData(Api.DUANZI_API, keywords, page);
                refreshLayout.finishRefresh(2000);
            }
        });
    }

    @Override
    public void onSuccess(ResponseBody responseBody) {

        try {
            String string = responseBody.string();
            SousuoBean sousuoBean = new Gson().fromJson(string, SousuoBean.class);
            data = sousuoBean.getData();
            Log.d("SousuoActivity", "data:" + data);
            MyAdapter myAdapter = new MyAdapter(this, data);
            mRecy.setAdapter(myAdapter);
            mRecy.setLayoutManager(new LinearLayoutManager(this));
            myAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onClick(int position) {
                    yunxing(position);
                }

                @Override
                public void onLongClick(int position) {
                    yunxing(position);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    private void yunxing(int position) {
        String images = data.get(position).getImages();
        String subhead = data.get(position).getSubhead();
        String title = data.get(position).getTitle();
        int pid = data.get(position).getPid();
        double pscid = data.get(position).getPscid();
        double price = data.get(position).getPrice();
        Intent intent = new Intent(SousuoActivity.this, SpxqActivity.class);
        intent.putExtra("images", images);
        intent.putExtra("subhead", subhead);
        intent.putExtra("title", title);
        intent.putExtra("pid", pid+"");
        intent.putExtra("pscid", pscid+"");
        intent.putExtra("price", price+"");
        startActivity(intent);

    }
    /**
     * 销毁
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (sousuoPresenter == null) {
            sousuoPresenter.dettachView();
        }
    }
}
SousuoBean页面

public class SousuoBean {

    /**
     * msg : 查询成功
     * code : 0
     * data : [{"bargainPrice":11800,"createtime":"2017-10-14T21:38:26","detailUrl":"https://mitem.jd.hk/ware/view.action?wareId=1988853309&cachekey=1acb07a701ece8d2434a6ae7fa6870a1","images":"https://m.360buyimg.com/n0/jfs/t6130/97/1370670410/180682/1109582a/593276b1Nd81fe723.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5815/178/2614671118/51656/7f52d137/593276c7N107b725a.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5878/60/2557817477/30873/4502b606/593276caN5a7d6357.jpg!q70.jpg","itemtype":1,"pid":80,"price":777,"pscid":40,"salenum":776,"sellerid":1,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP213英寸Bar i5/8G/256G"},{"bargainPrice":11800,"createtime":"2017-10-03T23:53:28","detailUrl":"https://mitem.jd.hk/ware/view.action?wareId=1988853309&cachekey=1acb07a701ece8d2434a6ae7fa6870a1","images":"https://m.360buyimg.com/n0/jfs/t6130/97/1370670410/180682/1109582a/593276b1Nd81fe723.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5815/178/2614671118/51656/7f52d137/593276c7N107b725a.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5878/60/2557817477/30873/4502b606/593276caN5a7d6357.jpg!q70.jpg","itemtype":0,"pid":79,"price":888,"pscid":40,"salenum":5454,"sellerid":23,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP213英寸Bar i5/8G/256G"},{"bargainPrice":11800,"createtime":"2017-10-14T21:38:26","detailUrl":"https://mitem.jd.hk/ware/view.action?wareId=1988853309&cachekey=1acb07a701ece8d2434a6ae7fa6870a1","images":"https://m.360buyimg.com/n0/jfs/t6130/97/1370670410/180682/1109582a/593276b1Nd81fe723.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5815/178/2614671118/51656/7f52d137/593276c7N107b725a.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5878/60/2557817477/30873/4502b606/593276caN5a7d6357.jpg!q70.jpg","itemtype":1,"pid":78,"price":999,"pscid":40,"salenum":656,"sellerid":22,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP213英寸Bar i5/8G/256G"},{"bargainPrice":11800,"createtime":"2017-10-10T17:33:37","detailUrl":"https://item.m.jd.com/product/4338107.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t6700/155/2098998076/156185/6cf95035/595dd5a5Nc3a7dab5.jpg!q70.jpg","itemtype":0,"pid":57,"price":5199,"pscid":40,"salenum":4343,"sellerid":1,"subhead":"i5 MX150 2G显存】全高清窄边框 8G内存 256固态硬盘 支持指纹识别 预装WIN10系统","title":"小米(MI)Air 13.3英寸全金属轻薄笔记本(i5-7200U 8G 256G PCle SSD MX150 2G独显 FHD 指纹识别 Win10)银 "},{"bargainPrice":5599,"createtime":"2017-10-10T17:30:32","detailUrl":"https://item.m.jd.com/product/4824715.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n12/jfs/t7768/184/1153704394/148460/f42e1432/599a930fN8a85626b.jpg!q70.jpg","itemtype":0,"pid":59,"price":5599,"pscid":40,"salenum":675,"sellerid":3,"subhead":"游戏本选择4G独显,拒绝掉帧】升级版IPS全高清防眩光显示屏,WASD方向键颜色加持,三大出风口立体散热!","title":"戴尔DELL灵越游匣15PR-6648B GTX1050 15.6英寸游戏笔记本电脑(i5-7300HQ 8G 128GSSD+1T 4G独显 IPS)"},{"bargainPrice":11800,"createtime":"2017-10-14T21:38:26","detailUrl":"https://item.m.jd.com/product/5025518.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t8830/106/1760940277/195595/5cf9412f/59bf2ef5N5ab7dc16.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5428/70/1520969931/274676/b644dd0d/591128e7Nd2f70da0.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5566/365/1519564203/36911/620c750c/591128eaN54ac3363.jpg!q70.jpg","itemtype":1,"pid":58,"price":6399,"pscid":40,"salenum":545,"sellerid":2,"subhead":"升级4G大显存!Nvme协议Pcie SSD,速度快人一步】GTX1050Ti就选拯救者!专业游戏键盘&新模具全新设计!","title":"联想(Lenovo)拯救者R720 15.6英寸游戏笔记本电脑(i5-7300HQ 8G 1T+128G SSD GTX1050Ti 4G IPS )"},{"bargainPrice":11800,"createtime":"2017-10-14T21:38:26","detailUrl":"https://mitem.jd.hk/ware/view.action?wareId=1988853309&cachekey=1acb07a701ece8d2434a6ae7fa6870a1","images":"https://m.360buyimg.com/n0/jfs/t6130/97/1370670410/180682/1109582a/593276b1Nd81fe723.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5815/178/2614671118/51656/7f52d137/593276c7N107b725a.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5878/60/2557817477/30873/4502b606/593276caN5a7d6357.jpg!q70.jpg","itemtype":1,"pid":63,"price":10000,"pscid":40,"salenum":3232,"sellerid":7,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP213英寸Bar i5/8G/256G"},{"bargainPrice":11800,"createtime":"2017-10-03T23:43:53","detailUrl":"https://mitem.jd.hk/ware/view.action?wareId=1988853309&cachekey=1acb07a701ece8d2434a6ae7fa6870a1","images":"https://m.360buyimg.com/n0/jfs/t6130/97/1370670410/180682/1109582a/593276b1Nd81fe723.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5815/178/2614671118/51656/7f52d137/593276c7N107b725a.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5878/60/2557817477/30873/4502b606/593276caN5a7d6357.jpg!q70.jpg","itemtype":0,"pid":64,"price":11000,"pscid":40,"salenum":0,"sellerid":8,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP213英寸Bar i5/8G/256G"},{"bargainPrice":11800,"createtime":"2017-10-14T21:48:08","detailUrl":"https://mitem.jd.hk/ware/view.action?wareId=1988853309&cachekey=1acb07a701ece8d2434a6ae7fa6870a1","images":"https://m.360buyimg.com/n0/jfs/t6130/97/1370670410/180682/1109582a/593276b1Nd81fe723.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5815/178/2614671118/51656/7f52d137/593276c7N107b725a.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5878/60/2557817477/30873/4502b606/593276caN5a7d6357.jpg!q70.jpg","itemtype":2,"pid":65,"price":12000,"pscid":40,"salenum":868,"sellerid":9,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP213英寸Bar i5/8G/256G"},{"bargainPrice":11800,"createtime":"2017-10-14T21:38:26","detailUrl":"https://mitem.jd.hk/ware/view.action?wareId=1988853309&cachekey=1acb07a701ece8d2434a6ae7fa6870a1","images":"https://m.360buyimg.com/n0/jfs/t6130/97/1370670410/180682/1109582a/593276b1Nd81fe723.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5815/178/2614671118/51656/7f52d137/593276c7N107b725a.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5878/60/2557817477/30873/4502b606/593276caN5a7d6357.jpg!q70.jpg","itemtype":1,"pid":66,"price":13000,"pscid":40,"salenum":7676,"sellerid":10,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP213英寸Bar i5/8G/256G"}]
     * page : 1
     */

    private String msg;
    private String code;
    private String page;
    private List<DataBean> data;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getPage() {
        return page;
    }

    public void setPage(String page) {
        this.page = page;
    }

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean {
        /**
         * bargainPrice : 11800
         * createtime : 2017-10-14T21:38:26
         * detailUrl : https://mitem.jd.hk/ware/view.action?wareId=1988853309&cachekey=1acb07a701ece8d2434a6ae7fa6870a1
         * images : https://m.360buyimg.com/n0/jfs/t6130/97/1370670410/180682/1109582a/593276b1Nd81fe723.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5815/178/2614671118/51656/7f52d137/593276c7N107b725a.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5878/60/2557817477/30873/4502b606/593276caN5a7d6357.jpg!q70.jpg
         * itemtype : 1
         * pid : 80
         * price : 777
         * pscid : 40
         * salenum : 776
         * sellerid : 1
         * subhead : 购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)
         * title : 全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP213英寸Bar i5/8G/256G
         */

        private double bargainPrice;
        private String createtime;
        private String detailUrl;
        private String images;
        private double itemtype;
        private int pid;
        private double price;
        private double pscid;
        private double salenum;
        private double sellerid;
        private String subhead;
        private String title;

        public double getBargainPrice() {
            return bargainPrice;
        }

        public void setBargainPrice(double bargainPrice) {
            this.bargainPrice = bargainPrice;
        }

        public String getCreatetime() {
            return createtime;
        }

        public void setCreatetime(String createtime) {
            this.createtime = createtime;
        }

        public String getDetailUrl() {
            return detailUrl;
        }

        public void setDetailUrl(String detailUrl) {
            this.detailUrl = detailUrl;
        }

        public String getImages() {
            return images;
        }

        public void setImages(String images) {
            this.images = images;
        }

        public double getItemtype() {
            return itemtype;
        }

        public void setItemtype(double itemtype) {
            this.itemtype = itemtype;
        }

        public int getPid() {
            return pid;
        }

        public void setPid(int pid) {
            this.pid = pid;
        }

        public double getPrice() {
            return price;
        }

        public void setPrice(double price) {
            this.price = price;
        }

        public double getPscid() {
            return pscid;
        }

        public void setPscid(double pscid) {
            this.pscid = pscid;
        }

        public double getSalenum() {
            return salenum;
        }

        public void setSalenum(int salenum) {
            this.salenum = salenum;
        }

        public double getSellerid() {
            return sellerid;
        }

        public void setSellerid(double sellerid) {
            this.sellerid = sellerid;
        }

        public String getSubhead() {
            return subhead;
        }

        public void setSubhead(String subhead) {
            this.subhead = subhead;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }
    }
}
SpxqActivity页面

public class SpxqActivity extends AppCompatActivity implements TianjiaView {

    @BindView(R.id.spxq_sim)
    SimpleDraweeView spxq_sim;
    @BindView(R.id.spxq_textView1)
    TextView spxq_textView1;
    @BindView(R.id.spxq_textView2)
    TextView spxq_textView2;
    @BindView(R.id.spxq_button)
    Button spxqButton;
    private String pid;
    private TianjiaPresenter tianjiaPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spxq);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        String images = intent.getStringExtra("images");
        if (images.indexOf("|") != -1) {
            String result = images.substring(0, images.indexOf("|"));
            //加载图片  url=result
            spxq_sim.setImageURI(result);
        } else {
            //加载图片  url=iamges
            spxq_sim.setImageURI(images);
        }
        String subhead = intent.getStringExtra("subhead");
        spxq_textView1.setText(subhead);
        String title = intent.getStringExtra("title");
        spxq_textView2.setText(title);
        pid = intent.getStringExtra("pid");
        String pscid = intent.getStringExtra("pscid");
        String price = intent.getStringExtra("price");

        Log.d("SpxqActivity", pid);
        Log.d("SpxqActivity", pscid);
        Log.d("SpxqActivity", price);
    }

    @Override
    public void onSuccess(ResponseBody responseBody) {
        try {
            String string = responseBody.string();
            Toast.makeText(this, "成功", Toast.LENGTH_SHORT).show();

            Log.d("SpxqActivity___", string.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.spxq_button)
    public void onViewClicked() {
        tianjiaPresenter = new TianjiaPresenter();
        tianjiaPresenter.attachView(this);
        tianjiaPresenter.getData(Api.DUANZI_API2, pid);

    }
    /**
     * 销毁
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (tianjiaPresenter == null) {
            tianjiaPresenter.dettachView();
        }
    }
}
TuYi页面

public class TuYi extends AppCompatActivity {
    @BindView(R.id.edit)
    EditText editText;
    @BindView(R.id.tv_sou)
    TextView tv;
    @BindView(R.id.id_flowlayout)
    FlowLayout mFlowLayout;
    @BindView(R.id.clear)
    Button clear;
    private String[] mVals = new String[]{};
    private LayoutInflater mInflater;
    private String s;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tu_yi);
        mInflater = LayoutInflater.from(this);
        ButterKnife.bind(this);
        //设置默认显示
        for (int i = 0; i < mVals.length; i++) {
            tv = (TextView) mInflater.inflate(R.layout.search_label_tv, mFlowLayout, false);
            tv.setText(mVals[i]);
            final String str = tv.getText().toString();
            //点击事件
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(TuYi.this, "你点击了" + str, Toast.LENGTH_SHORT).show();
                }
            });
            mFlowLayout.addView(tv);//添加到父View
        }
    }

    @OnClick({R.id.tv_sou, R.id.id_flowlayout, R.id.clear})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.tv_sou:
                s = editText.getText().toString();

                tv = (TextView) mInflater.inflate(
                        R.layout.search_label_tv, mFlowLayout, false);
                tv.setText(s);
                final String str = tv.getText().toString();
                //点击事件
                tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(TuYi.this, "00你点击了" + str, Toast.LENGTH_SHORT).show();
                    }
                });
                mFlowLayout.addView(tv);//添加到父View
                Intent intent = new Intent(TuYi.this, SousuoActivity.class);
                intent.putExtra("keywords",s);
                startActivity(intent);
                break;
            case R.id.id_flowlayout:
                break;
            case R.id.clear:
                mFlowLayout.removeAllViews();
                break;
        }
    }
}
tianjiagouwuche里的
TianjiaModel页面
public class TianjiaModel {
    private TianjiaZiP sousuoZiP;

    public TianjiaModel(TianjiaZiP sousuoZiP) {
        this.sousuoZiP = sousuoZiP;
    }

    // https://www.zhaoapi.cn/product/addCart?uid=15157&pid=80&token=C7C24A80854F96DB50620EB5507F0878
    public void getData(String url, String key) {
        Map<String, String> parmars = new HashMap<>();
        parmars.put("uid", "15157");
        parmars.put("pid", key);
        parmars.put("token", "C7C24A80854F96DB50620EB5507F0878");
        parmars.put("source", "android");

        RetrofitHelper.getApiService(Api.BASE_API).doGet(url, parmars)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.d("TianjiaModel3", "失败");
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        sousuoZiP.onSuccess(responseBody);
                        Log.d("TianjiaModel", "cg");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d("TianjiaModel2", "失败");
                    }

                    @Override
                    public void onComplete() {
                        Log.d("TianjiaModel1", "失败");
                    }
                });
    }
}
TianjiaPresenter页面

public class TianjiaPresenter implements TianjiaZiP {

    private TianjiaModel sousuoModel;
    private TianjiaView sousuoView;

    public TianjiaPresenter(){
        sousuoModel = new TianjiaModel(this);
    }

    public void attachView(TianjiaView iDuanZiView){
        this.sousuoView = iDuanZiView;
    }

    public void dettachView(){
        if (sousuoView != null){
            sousuoView = null;
        }
    }

    public void getData(String url,String key){
        sousuoModel.getData(url,key);
    }

    @Override
    public void onSuccess(ResponseBody responseBody) {
        sousuoView.onSuccess(responseBody);
    }
}
 
 
TianjiaView接口页面

public interface TianjiaView {
    void onSuccess(ResponseBody responseBody);
}
TianjiaZiP接口页面

public interface TianjiaZiP {
    void onSuccess(ResponseBody responseBody);
}
mvp里的
SousuoModel页面
public class SousuoModel {
    private SousuoZiP sousuoZiP;

    public SousuoModel(SousuoZiP sousuoZiP) {
        this.sousuoZiP = sousuoZiP;
    }

    public void getData(String url,String key, int page) {
        Map<String, String> parmars = new HashMap<>();
        parmars.put("keywords", key);
        parmars.put("page", page+"");
        RetrofitHelper.getApiService(Api.BASE_API).doGet(url, parmars)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        sousuoZiP.onSuccess(responseBody);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}

SousuoPresenter页面

public class SousuoPresenter implements SousuoZiP {

    private SousuoModel sousuoModel;
    private SousuoView sousuoView;

    public SousuoPresenter(){
        sousuoModel = new SousuoModel(this);
    }

    public void attachView(SousuoView iDuanZiView){
        this.sousuoView = iDuanZiView;
    }

    public void dettachView(){
        if (sousuoView != null){
            sousuoView = null;
        }
    }

    public void getData(String url,String key,int page){
        sousuoModel.getData(url,key,page);
    }

    @Override
    public void onSuccess(ResponseBody responseBody) {
        sousuoView.onSuccess(responseBody);
    }
}
 
 
SousuoView接口页面

public interface SousuoView {
    void onSuccess(ResponseBody responseBody);
}
SousuoZiP接口页面

public interface SousuoZiP {
    void onSuccess(ResponseBody responseBody);
}
 
 
TianjiaModel页面

public class TianjiaModel {
    private TianjiaZiP sousuoZiP;

    public TianjiaModel(TianjiaZiP sousuoZiP) {
        this.sousuoZiP = sousuoZiP;
    }

    // https://www.zhaoapi.cn/product/addCart?uid=15157&pid=80&token=C7C24A80854F96DB50620EB5507F0878
    public void getData(String url, String key) {
        Map<String, String> parmars = new HashMap<>();
        parmars.put("uid", "15157");
        parmars.put("pid", key);
        parmars.put("token", "C7C24A80854F96DB50620EB5507F0878");
        parmars.put("source", "android");

        RetrofitHelper.getApiService(Api.BASE_API).doGet(url, parmars)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.d("TianjiaModel3", "失败");
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        sousuoZiP.onSuccess(responseBody);
                        Log.d("TianjiaModel", "cg");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d("TianjiaModel2", "失败");
                    }

                    @Override
                    public void onComplete() {
                        Log.d("TianjiaModel1", "失败");
                    }
                });
    }
}

TianjiaPresenter页面

public class TianjiaPresenter implements TianjiaZiP {

    private TianjiaModel sousuoModel;
    private TianjiaView sousuoView;

    public TianjiaPresenter(){
        sousuoModel = new TianjiaModel(this);
    }

    public void attachView(TianjiaView iDuanZiView){
        this.sousuoView = iDuanZiView;
    }

    public void dettachView(){
        if (sousuoView != null){
            sousuoView = null;
        }
    }

    public void getData(String url,String key){
        sousuoModel.getData(url,key);
    }

    @Override
    public void onSuccess(ResponseBody responseBody) {
        sousuoView.onSuccess(responseBody);
    }
}
 
 
TianjiaView接口页面

public interface TianjiaView {
    void onSuccess(ResponseBody responseBody);
}
 
 
TianjiaZiP接口页面

public interface TianjiaZiP {
    void onSuccess(ResponseBody responseBody);
}
yuyi下的api的
Api页面
public class Api {
    //https://www.zhaoapi.cn/product/searchProducts?keywords=笔记本&page=1
    public static final String BASE_API = "https://www.zhaoapi.cn/";
    public static final String DUANZI_API = "product/searchProducts";
    public static final String DUANZI_API2 = "product/addCart";

}
api下的ApiService页面

public interface ApiService {
    @GET
    Observable<ResponseBody> doGet(@Url String url, @QueryMap Map<String, String> map);
}
api下的
RetrofitHelper页面
public class RetrofitHelper {
    public static OkHttpClient okHttpClient;
    public static ApiService apiService;

    static {
        getOkHttpClient();
    }

    private static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null){
            synchronized (OkHttpClient.class){
                if (okHttpClient == null){
                    File file = new File(Environment.getExternalStorageDirectory(),"cahce");
                    long fileSize = 10*1024*1024;
                    okHttpClient = new OkHttpClient.Builder()
                            .readTimeout(15, TimeUnit.SECONDS)
                            .writeTimeout(15,TimeUnit.SECONDS)
                            .connectTimeout(15,TimeUnit.SECONDS)
                            .cache(new Cache(file,fileSize))
                            .build();
                }
            }
        }
        return okHttpClient;
    }

    public static ApiService getApiService(String url){
        if (apiService == null){
            synchronized (OkHttpClient.class){
                apiService = createApiService(ApiService.class,url);
            }
        }
        return apiService;
    }

    private static <T>T createApiService(Class<T> tClass, String url) {
        T t = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)
                .build()
                .create(tClass);
        return t;
    }
}
tuer下的api的Apii页面
 
 
public class Apii {
    //https://www.zhaoapi.cn/product/getCarts?uid=15157&source=android
    public static final String BASE_API = "https://www.zhaoapi.cn/";
    public static final String DUANZI_API = "product/getCarts";
}
tuer下的api的
ApiServicei接口
public interface ApiServicei {
    @GET
    Observable<ResponseBody> doGet(@Url String url, @QueryMap Map<String, String> map);
}

tuer下的mvp的
MyExpandAdapter页面
public class MyExpandAdapter extends BaseExpandableListAdapter {
    private List<ShoppCarBean.DataBean> data;
    private Context context;
    private ModifyGoodsItemNumberListener modifyGoodsItemNumberListener;
    private CheckGroupItemListener checkGroupItemListener;
    //接收是否处于编辑状态的一个boolean    private boolean isEditor;

    //商家以及商品是否被选中的一个监听
    public void setCheckGroupItemListener(CheckGroupItemListener checkGroupItemListener){
        this.checkGroupItemListener = checkGroupItemListener;
    }

    //设置商品的加减监听
    public void setModifyGoodsItemNumberListener(ModifyGoodsItemNumberListener modifyGoodsItemNumberListener){
        this.modifyGoodsItemNumberListener = modifyGoodsItemNumberListener;
    }

    //是否显示删除按钮
    public void showDeleteButton(boolean isEditor){
        this.isEditor = isEditor;
        //刷新适配器
        notifyDataSetChanged();
    }

    public MyExpandAdapter(Context context) {
        this.context = context;
    }
    public void setList(List<ShoppCarBean.DataBean> data){
        this.data=data;
        notifyDataSetChanged();
    }
    @Override
    public int getGroupCount() {
        return data !=null?data.size() :0;
    }

    @Override
    public int getChildrenCount(int i) {
        return data!=null&&data.get(i).getList()!=null?data.get(i).getList().size() :0;
    }

    @Override
    public Object getGroup(int i) {
        return data.get(i);
    }

    @Override
    public Object getChild(int i, int i1) {
        return data.get(i).getList().get(i1);
    }

    @Override
    public long getGroupId(int i) {
        return i;
    }

    @Override
    public long getChildId(int i, int i1) {
        return i1;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getGroupView(final int groupPosition, boolean b, View view, ViewGroup viewGroup) {
        if(view==null){
            view= LayoutInflater.from(context).inflate(R.layout.layout_group_item,viewGroup,false);
        }
        CheckBox ck_group_choosed = view.findViewById(R.id.ck_group_choosed);
        ck_group_choosed.setText(data.get(groupPosition).getSellerName());

        if(data.get(groupPosition).isGroupChoosed()){
            ck_group_choosed.setChecked(true);
        }else{
            ck_group_choosed.setChecked(false);
        }

        //ck_group_choosed.setChan
        ck_group_choosed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkGroupItemListener.checkGroupItem(groupPosition,((CheckBox)view).isChecked());
            }
        });
        return view;
    }

    @Override
    public View getChildView(final int i, final int i1, boolean b, View view, ViewGroup viewGroup) {

        if(view==null){
            view=LayoutInflater.from(context).inflate(R.layout.layout_child_item,viewGroup,false);

        }
        //商品选择
        CheckBox ck_child_choosed = view.findViewById(R.id.ck_child_choose);
        //商品图片
        ImageView iv_show_pic = view.findViewById(R.id.iv_show_pic);
        //商品主标题
        TextView tv_commodity_name = view.findViewById(R.id.tv_commodity_name);
        //商品副标题
        TextView tv_commodity_attr = view.findViewById(R.id.tv_commodity_attr);
        //商品价格
        TextView tv_commodity_price = view.findViewById(R.id.tv_commodity_price);
        //商品数量
        TextView tv_commodity_num = view.findViewById(R.id.tv_commodity_num);
        //商品减
        TextView iv_sub = view.findViewById(R.id.iv_sub);
        //商品加减中的数量变化
        final TextView tv_commodity_show_num = view.findViewById(R.id.tv_commodity_show_num);
        //商品加
        TextView iv_add = view.findViewById(R.id.iv_add);
        //删除按钮
        Button btn_commodity_delete = view.findViewById(R.id.btn_commodity_delete);

        //设置文本信息
        tv_commodity_name.setText(data.get(i).getList().get(i1).getTitle());
        tv_commodity_attr.setText(data.get(i).getList().get(i1).getSubhead());
        tv_commodity_price.setText(""+data.get(i).getList().get(i1).getPrice());
        tv_commodity_num.setText("x"+data.get(i).getList().get(i1).getNum());
        tv_commodity_show_num.setText(data.get(i).getList().get(i1).getNum()+"");

        //分割图片地址
        String images = data.get(i).getList().get(i1).getImages();

        String[] urls = images.split("\\|");

        //加载商品图片
        Glide.with(context)
                .load(urls[0])
                .crossFade()
                .into(iv_show_pic);

//商品加
        iv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                modifyGoodsItemNumberListener.doIncrease(i,i1,tv_commodity_show_num);
            }
        });

        //设置商品加减的按钮
        //商品减
        iv_sub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                modifyGoodsItemNumberListener.doDecrease(i,i1,tv_commodity_show_num);

            }
        });

        //商品复选框是否被选中
        ck_child_choosed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //isChecked false  true
                checkGroupItemListener.checkChildItem(i,i1,((CheckBox)view).isChecked());
            }
        });

        //处理商品的选中状态
        if(data.get(i).getList().get(i1).isChildChoosed()){
            ck_child_choosed.setChecked(true);
        }else{
            ck_child_choosed.setChecked(false);
        }

        //控制删除按钮的隐藏与显示
        if(isEditor){
            btn_commodity_delete.setVisibility(View.VISIBLE);
        }else{
            btn_commodity_delete.setVisibility(View.GONE);
        }
        return view;
    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return false;
    }
    public interface CheckGroupItemListener{
        //商家的条目的复选框监听
        void checkGroupItem(int groupPosition, boolean isChecked);
        //商品的
        void checkChildItem(int groupPosition, int childPosition, boolean isChecked);

    }

    /**
     * 商品加减接口
     */
    public interface ModifyGoodsItemNumberListener{

        //商品添加操作
        void doIncrease(int groupPosition, int childPosition, View view);
        //商品减少操作
        void doDecrease(int groupPosition, int childPosition, View view);

    }
}
mvp下的ShoppCarBean页面

public class ShoppCarBean {
    /**
     * msg : 请求成功
     * code : 0
     * data : */

    private String msg;
    private String code;
    private List<DataBean> data;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean {
        /**
         * list :   * sellerName : 商家1
         * sellerid : 1
         */

        private String sellerName;
        private String sellerid;
        private List<ListBean> list;

        //商家是否被选中 组条目是否被选中
        private boolean isGroupChoosed;

        public boolean isGroupChoosed() {
            return isGroupChoosed;
        }

        public String getSellerName() {
            return sellerName;
        }

        public void setSellerName(String sellerName) {
            this.sellerName = sellerName;
        }

        public String getSellerid() {
            return sellerid;
        }

        public void setSellerid(String sellerid) {
            this.sellerid = sellerid;
        }

        public List<ListBean> getList() {
            return list;
        }

        public void setList(List<ListBean> list) {
            this.list = list;
        }

        public void setGroupChoosed(boolean groupChoosed) {
            isGroupChoosed = groupChoosed;
        }


        public static class ListBean {
            /**
             * bargainPrice : 99.0
             * createtime : 2017-10-14T21:38:26
             * detailUrl
             * images :.jpg
             * num : 1
             * pid : 45
             * price : 2999.0
             * pscid : 39
             * selected : 0
             * sellerid : 1
             * subhead : 高清双摄,就是清晰!2000+1600万高清摄像头,6GB大内存+高通骁龙835处理器,性能怪兽!
             * title : 一加手机5 (A5000) 6GB+64GB 月岩灰 全网通 双卡双待 移动联通电信4G手机
             */

            private double bargainPrice;
            private String createtime;
            private String detailUrl;
            private String images;
            private int num;
            private int pid;
            private double price;
            private int pscid;
            private int selected;
            private int sellerid;
            private String subhead;
            private String title;

            //子条目商品是否被选中的一个字段状态
            private boolean isChildChoosed;

            public boolean isChildChoosed() {
                return isChildChoosed;
            }
            public double getBargainPrice() {
                return bargainPrice;
            }

            public void setBargainPrice(double bargainPrice) {
                this.bargainPrice = bargainPrice;
            }

            public String getCreatetime() {
                return createtime;
            }

            public void setCreatetime(String createtime) {
                this.createtime = createtime;
            }

            public String getDetailUrl() {
                return detailUrl;
            }

            public void setDetailUrl(String detailUrl) {
                this.detailUrl = detailUrl;
            }

            public String getImages() {
                return images;
            }

            public void setImages(String images) {
                this.images = images;
            }

            public int getNum() {
                return num;
            }

            public void setNum(int num) {
                this.num = num;
            }

            public int getPid() {
                return pid;
            }

            public void setPid(int pid) {
                this.pid = pid;
            }

            public double getPrice() {
                return price;
            }

            public void setPrice(double price) {
                this.price = price;
            }

            public int getPscid() {
                return pscid;
            }

            public void setPscid(int pscid) {
                this.pscid = pscid;
            }

            public int getSelected() {
                return selected;
            }

            public void setSelected(int selected) {
                this.selected = selected;
            }

            public int getSellerid() {
                return sellerid;
            }

            public void setSellerid(int sellerid) {
                this.sellerid = sellerid;
            }

            public String getSubhead() {
                return subhead;
            }

            public void setSubhead(String subhead) {
                this.subhead = subhead;
            }

            public String getTitle() {
                return title;
            }

            public void setTitle(String title) {
                this.title = title;
            }


            public void setChildChoosed(boolean childChoosed) {
                isChildChoosed = childChoosed;
            }
        }
    }
}
mvp下的
TuEr页面
public class TuEr extends AppCompatActivity implements SpxqView,MyExpandAdapter.ModifyGoodsItemNumberListener,MyExpandAdapter.CheckGroupItemListener{
    @BindView(R.id.btnBack)
    TextView mBtnBack;
    @BindView(R.id.btnEditor)
    TextView mBtnEditor;
    @BindView(R.id.expandList)
    ExpandableListView mExpandList;
    @BindView(R.id.btnCheckAll)
    CheckBox mBtnCheckAll;
    @BindView(R.id.tvTotalPrice)
    TextView mTvTotalPrice;
    @BindView(R.id.btnAmount)
    TextView mBtnAmount;
    //默认是false
    private boolean flag;
    //购买商品的总数量
    private int totalNum = 0;
    //购买商品的总价
    private double totalPrice = 0.00;
    private List<ShoppCarBean.DataBean> list;
    private MyExpandAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tu_er);
        initView();
        mBtnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        getSupportActionBar().hide();
        mExpandList.setGroupIndicator(null);
        SpxqPresenter spxqPresenter = new SpxqPresenter();
        spxqPresenter.attachView(this);
        spxqPresenter.getData(Apii.DUANZI_API, "15157");
        adapter = new MyExpandAdapter(this);
        mExpandList.setAdapter(adapter);
        adapter.setModifyGoodsItemNumberListener(this);
        //设置商家以及商品是否被选中的监听
        adapter.setCheckGroupItemListener(this);
        mBtnCheckAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isChoosedAll(((CheckBox) view).isChecked());
                //计算商品总价
                statisticsPrice();
            }
        });
        mBtnEditor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!flag) {//编辑 -> 完成\
                    flag = true;
                    mBtnEditor.setText("完成");
                    adapter.showDeleteButton(flag);
                } else {
                    flag = false;
                    mBtnEditor.setText("编辑");
                    adapter.showDeleteButton(flag);
                }
            }
        });
    }
    private void initView() {
        mBtnBack = (TextView) findViewById(R.id.btnBack);
        mBtnEditor = (TextView) findViewById(R.id.btnEditor);
        mExpandList = (ExpandableListView) findViewById(R.id.expandList);
        mBtnCheckAll = (CheckBox) findViewById(R.id.btnCheckAll);
        mTvTotalPrice = (TextView) findViewById(R.id.tvTotalPrice);
        mBtnAmount = (TextView) findViewById(R.id.btnAmount);
    }

    @Override
    public void onSuccess(ResponseBody responseBody) {
        try {
            String string = responseBody.string();
            ShoppCarBean shoppCarBean = new Gson().fromJson(string, ShoppCarBean.class);
            List<ShoppCarBean.DataBean> data = shoppCarBean.getData();

            this.list = data;
            adapter.setList(list);
            defaultExpand();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void defaultExpand() {
        for (int i = 0; i < adapter.getGroupCount(); i++) {
            mExpandList.expandGroup(i);
        }
    }
    @Override
    public void doIncrease(int groupPosition, int childPosition, View view) {
        ShoppCarBean.DataBean.ListBean listBean = list.get(groupPosition).getList().get(childPosition);
        //取出当前的商品数量
        int currentNum = listBean.getNum();
        //商品++
        currentNum++;
        //将商品数量设置javabean        listBean.setNum(currentNum);

        //刷新适配器
        adapter.notifyDataSetChanged();


        //计算商品价格
        statisticsPrice();
    }

    @Override
    public void doDecrease(int groupPosition, int childPosition, View view) {
        ShoppCarBean.DataBean.ListBean listBean = list.get(groupPosition).getList().get(childPosition);
        //取出当前的商品数量
        int currentNum = listBean.getNum();
        //直接结束这个方法
        if (currentNum == 1) {
            return;
        }

        currentNum--;
        listBean.setNum(currentNum);
        //刷新适配器
        adapter.notifyDataSetChanged();

        //计算商品价格
        statisticsPrice();

    }

    @Override
    public void checkGroupItem(int groupPosition, boolean isChecked) {
        ShoppCarBean.DataBean dataBean = list.get(groupPosition);
        dataBean.setGroupChoosed(isChecked);

        //遍历商家里面的商品,将其置为选中状态
        for (ShoppCarBean.DataBean.ListBean listBean : dataBean.getList()) {
            listBean.setChildChoosed(isChecked);
        }

        //底部结算那个checkbox状态(全选)
        if (isCheckAll()) {
            mBtnCheckAll.setChecked(true);
        } else {
            mBtnCheckAll.setChecked(false);
        }

        //刷新适配器
        adapter.notifyDataSetChanged();

        //计算价格
        statisticsPrice();
    }

    @Override
    public void checkChildItem(int groupPosition, int childPosition, boolean isChecked) {
        ShoppCarBean.DataBean dataBean = list.get(groupPosition);//商家那一层
        List<ShoppCarBean.DataBean.ListBean> listBeans = dataBean.getList();
        ShoppCarBean.DataBean.ListBean listBean = listBeans.get(childPosition);

        //你点击商家的商品条目将其选中状态记录
        listBean.setChildChoosed(isChecked);

        //检测商家里面的每一个商品是否被选中,如果被选中,返回boolean
        boolean result = isGoodsCheckAll(groupPosition);
        if (result) {
            dataBean.setGroupChoosed(result);
        } else {
            dataBean.setGroupChoosed(result);
        }

        //底部结算那个checkbox状态(全选)
        if (isCheckAll()) {
            mBtnCheckAll.setChecked(true);
        } else {
            mBtnCheckAll.setChecked(false);
        }


        //刷新适配器
        adapter.notifyDataSetChanged();

        //计算总价
        statisticsPrice();

    }
    //购物车商品是否全部选中
    private boolean isCheckAll() {

        for (ShoppCarBean.DataBean dataBean : list) {
            if (!dataBean.isGroupChoosed()) {
                return false;
            }
        }
        return true;
    }
    //全选与反选
    private void isChoosedAll(boolean isChecked) {

        for (ShoppCarBean.DataBean dataBean : list) {
            dataBean.setGroupChoosed(isChecked);
            for (ShoppCarBean.DataBean.ListBean listBean : dataBean.getList()) {
                listBean.setChildChoosed(isChecked);
            }
        }
        //刷新适配器
        adapter.notifyDataSetChanged();
    }
    /**
     * 检测某个商家的商品是否都选中,如果都选中的话,商家CheckBox应该是选中状态
     */
    private boolean isGoodsCheckAll(int groupPosition) {
        List<ShoppCarBean.DataBean.ListBean> listBeans = this.list.get(groupPosition).getList();
        //遍历某一个商家的每个商品是否被选中
        for (ShoppCarBean.DataBean.ListBean listBean : listBeans) {
            if (listBean.isChildChoosed()) {//是选中状态
                continue;
            } else {
                return false;
            }
        }
        return true;
    }
    private void statisticsPrice() {
        //初始化值
        totalNum = 0;
        totalPrice = 0.00;
        for (ShoppCarBean.DataBean dataBean : list) {

            for (ShoppCarBean.DataBean.ListBean listBean : dataBean.getList()) {
                if (listBean.isChildChoosed()) {
                    totalNum++;
                    System.out.println("number : " + totalNum);
                    totalPrice += listBean.getNum() * listBean.getPrice();
                }
            }
        }
        //设置文本信息 合计、结算的商品数量
        mTvTotalPrice.setText("合计:" + totalPrice);
        mBtnAmount.setText("结算(" + totalNum + ")");
    }
}
SpxqModel页面

public class SpxqModel {
    private SpxqZiP sousuoZiP;

    public SpxqModel(SpxqZiP sousuoZiP) {
        this.sousuoZiP = sousuoZiP;
    }

    public void getData(String url,String key) {
        Map<String, String> parmars = new HashMap<>();
        parmars.put("uid", "15157");
        parmars.put("source", "android");
        RetrofitHelper.getApiService(Api.BASE_API).doGet(url, parmars)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        sousuoZiP.onSuccess(responseBody);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
SpxqPresenter页面

public class SpxqPresenter implements SpxqZiP {

    private SpxqModel spxqModel;
    private SpxqView spxqView;

    public SpxqPresenter(){
        spxqModel = new SpxqModel(this);
    }

    public void attachView(SpxqView iDuanZiView){
        this.spxqView = iDuanZiView;
    }

    public void dettachView(){
        if (spxqView != null){
            spxqView = null;
        }
    }

    public void getData(String url,String key){
        spxqModel.getData(url,key);
    }

    @Override
    public void onSuccess(ResponseBody responseBody) {
        spxqView.onSuccess(responseBody);
    }
}
 
 
SpxqView 接口页面

public interface SpxqView {
    void onSuccess(ResponseBody responseBody);
}
 
 
 SpxqZiP接口页面
public interface SpxqZiP {
    void onSuccess(ResponseBody responseBody);
}
dao下的
DaoMaster页面
public class DaoMaster extends AbstractDaoMaster {
    public static final int SCHEMA_VERSION = 1;

    /** Creates underlying database table using DAOs. */
    public static void createAllTables(Database db, boolean ifNotExists) {
        HistoricalBeanDao.createTable(db, ifNotExists);
    }

    /** Drops underlying database table using DAOs. */
    public static void dropAllTables(Database db, boolean ifExists) {
        HistoricalBeanDao.dropTable(db, ifExists);
    }

    /**
     * WARNING: Drops all table on Upgrade! Use only during development.
     * Convenience method using a {@link DevOpenHelper}.
     */
    public static DaoSession newDevSession(Context context, String name) {
        Database db = new DevOpenHelper(context, name).getWritableDb();
        DaoMaster daoMaster = new DaoMaster(db);
        return daoMaster.newSession();
    }

    public DaoMaster(SQLiteDatabase db) {
        this(new StandardDatabase(db));
    }

    public DaoMaster(Database db) {
        super(db, SCHEMA_VERSION);
        registerDaoClass(HistoricalBeanDao.class);
    }

    public DaoSession newSession() {
        return new DaoSession(db, IdentityScopeType.Session, daoConfigMap);
    }

    public DaoSession newSession(IdentityScopeType type) {
        return new DaoSession(db, type, daoConfigMap);
    }

    /**
     * Calls {@link #createAllTables(Database, boolean)} in {@link #onCreate(Database)} -
     */
    public static abstract class OpenHelper extends DatabaseOpenHelper {
        public OpenHelper(Context context, String name) {
            super(context, name, SCHEMA_VERSION);
        }

        public OpenHelper(Context context, String name, CursorFactory factory) {
            super(context, name, factory, SCHEMA_VERSION);
        }

        @Override
        public void onCreate(Database db) {
            Log.i("greenDAO", "Creating tables for schema version " + SCHEMA_VERSION);
            createAllTables(db, false);
        }
    }

    /** WARNING: Drops all table on Upgrade! Use only during development. */
    public static class DevOpenHelper extends OpenHelper {
        public DevOpenHelper(Context context, String name) {
            super(context, name);
        }

        public DevOpenHelper(Context context, String name, CursorFactory factory) {
            super(context, name, factory);
        }

        @Override
        public void onUpgrade(Database db, int oldVersion, int newVersion) {
            Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
            dropAllTables(db, true);
            onCreate(db);
        }
    }

}
dao下的
DaoSession页面
public class DaoSession extends AbstractDaoSession {

    private final DaoConfig historicalBeanDaoConfig;

    private final HistoricalBeanDao historicalBeanDao;

    public DaoSession(Database db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>
            daoConfigMap) {
        super(db);

        historicalBeanDaoConfig = daoConfigMap.get(HistoricalBeanDao.class).clone();
        historicalBeanDaoConfig.initIdentityScope(type);

        historicalBeanDao = new HistoricalBeanDao(historicalBeanDaoConfig, this);

        registerDao(HistoricalBean.class, historicalBeanDao);
    }
    
    public void clear() {
        historicalBeanDaoConfig.clearIdentityScope();
    }

    public HistoricalBeanDao getHistoricalBeanDao() {
        return historicalBeanDao;
    }

}
dao下的
HistoricalBeanDao页面
public class HistoricalBeanDao extends AbstractDao<HistoricalBean, Long> {

    public static final String TABLENAME = "HISTORICAL_BEAN";

    /**
     * Properties of entity HistoricalBean.<br/>
     * Can be used for QueryBuilder and for referencing column names.
     */
    public static class Properties {
        public final static Property Id = new Property(0, Long.class, "id", true, "_id");
        public final static Property Name = new Property(1, String.class, "name", false, "NAME");
    }


    public HistoricalBeanDao(DaoConfig config) {
        super(config);
    }
    
    public HistoricalBeanDao(DaoConfig config, DaoSession daoSession) {
        super(config, daoSession);
    }

    /** Creates the underlying database table. */
    public static void createTable(Database db, boolean ifNotExists) {
        String constraint = ifNotExists? "IF NOT EXISTS ": "";
        db.execSQL("CREATE TABLE " + constraint + "\"HISTORICAL_BEAN\" (" + //
                "\"_id\" INTEGER PRIMARY KEY ," + // 0: id
                "\"NAME\" TEXT UNIQUE );"); // 1: name
    }

    /** Drops the underlying database table. */
    public static void dropTable(Database db, boolean ifExists) {
        String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"HISTORICAL_BEAN\"";
        db.execSQL(sql);
    }

    @Override
    protected final void bindValues(DatabaseStatement stmt, HistoricalBean entity) {
        stmt.clearBindings();
 
        Long id = entity.getId();
        if (id != null) {
            stmt.bindLong(1, id);
        }
 
        String name = entity.getName();
        if (name != null) {
            stmt.bindString(2, name);
        }
    }

    @Override
    protected final void bindValues(SQLiteStatement stmt, HistoricalBean entity) {
        stmt.clearBindings();
 
        Long id = entity.getId();
        if (id != null) {
            stmt.bindLong(1, id);
        }
 
        String name = entity.getName();
        if (name != null) {
            stmt.bindString(2, name);
        }
    }

    @Override
    public Long readKey(Cursor cursor, int offset) {
        return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
    }    

    @Override
    public HistoricalBean readEntity(Cursor cursor, int offset) {
        HistoricalBean entity = new HistoricalBean( //
            cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
            cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1) // name
        );
        return entity;
    }
     
    @Override
    public void readEntity(Cursor cursor, HistoricalBean entity, int offset) {
        entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
        entity.setName(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
     }
    
    @Override
    protected final Long updateKeyAfterInsert(HistoricalBean entity, long rowId) {
        entity.setId(rowId);
        return rowId;
    }
    
    @Override
    public Long getKey(HistoricalBean entity) {
        if(entity != null) {
            return entity.getId();
        } else {
            return null;
        }
    }

    @Override
    public boolean hasKey(HistoricalBean entity) {
        return entity.getId() != null;
    }

    @Override
    protected final boolean isEntityUpdateable() {
        return true;
    }
    
}
bean下的
HistoricalBean页面
@Entity
public class HistoricalBean {
  @Id
  private Long id;
  @Unique
  private String name;
  @Generated(hash = 1063713278)
  public HistoricalBean(Long id, String name) {
      this.id = id;
      this.name = name;
  }
  @Generated(hash = 633459717)
  public HistoricalBean() {
  }
  public Long getId() {
      return this.id;
  }
  public void setId(Long id) {
      this.id = id;
  }
  public String getName() {
      return this.name;
  }
  public void setName(String name) {
      this.name = name;
  }

}
app下的
App页面
public class App extends Application {
    private DaoSession daoSession;
    private static App instance;
    @Override
    public void onCreate() {
        super.onCreate();
        Fresco.initialize(this);
    /*    x.Ext.init(this);
        x.Ext.setDebug(false);*/ //输出debug日志,开启会影响性能
        instance=this;
        initDao();
    }
    public static  App getInstance(){
        return instance;
    }
    private void initDao() {
        //创建数据库
        SQLiteDatabase db = new DaoMaster.DevOpenHelper(this, "data.db").getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
    }
    public DaoSession getDao(){
        return daoSession;
    }
}
依赖

 compile 'org.greenrobot:greendao:3.2.0'
    //图片
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.github.bumptech.glide:glide:3.6.1'
    compile 'com.facebook.fresco:fresco:1.8.1'
//Imageloader
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
//recyclerview
    compile 'com.android.support:recyclerview-v7:26+'
//butterknife
    compile 'com.jakewharton:butterknife:8.5.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
//BottomTabBar
    compile 'com.hjm:BottomTabBar:1.1.1'
    compile 'com.android.support:design:26+'
    compile 'com.youth.banner:banner:1.4.9'
    implementation 'com.squareup.okhttp3:okhttp:3.9.1'
    implementation 'com.google.code.gson:gson:2.8.+'
    //okHttp   2    compile 'com.squareup.okhttp3:okhttp:3.6.0'
    compile 'com.squareup.okio:okio:1.11.0'
    //rxjava
    compile 'io.reactivex.rxjava2:rxjava:2.0.7'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    //retrofit
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.squareup.retrofit2:converter-scalars:2.1.0'
    //一个刷新的依赖
    compile 'com.scwang.smartrefresh:SmartRefreshLayout:1.0.5.1'
    implementation 'com.sunfusheng:marqueeview:1.3.3'
    implementation 'com.jcodecraeer:xrecyclerview:1.3.2'
    //一个刷新的依赖
    compile 'com.scwang.smartrefresh:SmartRefreshLayout:1.0.5.1'
    compile 'org.xutils:xutils:3.3.36'
权限

<activity android:name=".tuer.TuEr"></activity>
<activity android:name=".tuyi.TuYi"></activity>
<activity android:name=".tuyi.SousuoActivity"></activity>
<activity android:name=".tuyi.SpxqActivity"></activity>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />



猜你喜欢

转载自blog.csdn.net/qq_41673730/article/details/80725777