京东 搜索 和 购物车

//考试依赖begin
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
implementation 'com.google.code.gson:gson:2.8.5'
//网络日志拦截器
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
implementation 'com.android.support:recyclerview-v7:28.0.0-alpha3'
implementation 'com.android.support:design:28.0.0-alpha3'
//RecyclerView 上啦加载下拉刷新 https://github.com/XRecyclerView/XRecyclerView
implementation('com.jcodecraeer:xrecyclerview:1.5.9') {
    exclude group: 'com.android.support'
}
//图片加载 https://github.com/nostra13/Android-Universal-Image-Loader/wiki/Quick-Setup
implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
//导入Glide版本记得使用此版本
implementation 'com.github.bumptech.glide:glide:3.8.0'
//轮播图 https://github.com/youth5201314/banner
implementation 'com.youth.banner:banner:1.4.10'
implementation 'com.fynn.fluidlayout:fluidlayout:1.0'
implementation 'com.hyman:flowlayout-lib:1.1.2'
MainActivity
public class MainActivity extends AppCompatActivity {
    private EditText editText;
    private Button button,lishi1;
    private FluidLayout fluidLayout;

    private TagFlowLayout last_tag;
    private KeyAdapter lastAdapter;
    //    private MainAdapter adapter;
    //    private ListView listView;
    //    private SqliteDao dao;
    //    private List<String> list;
    private List<String> list1;

    private String mNAME[] = {
            "考拉三周年人气热销榜",
            "电动牙刷",
            "尤妮佳",
            "豆豆鞋",
            "沐浴露",
            "日东红茶",
            "榴莲",
            "电动牙刷",
            "雅诗莱黛",
            "豆豆鞋"
    };

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


        initview();
    }

    private void initview() {
        editText = findViewById(R.id.souzhou);
        button = findViewById(R.id.sousuo);
        lishi1 = findViewById(R.id.btn_clear);
        fluidLayout = findViewById(R.id.liushi);
//        listView = findViewById(R.id.list_ite);
        //流式布局
        list1 = new ArrayList<>();
        list1.add("冰激淋");
        list1.add("麻辣小龙虾");
        list1.add("汉堡");
        list1.add("煎饼");
        last_tag = findViewById(R.id.hot_tag);
        lastAdapter = new KeyAdapter(list1);

        last_tag.setAdapter(lastAdapter);


        //数据库
//        = new Sq daoliteDao(this);
//        list = new ArrayList<>();
//        list  = dao.select();
//        list.clear();
//        adapter = new MainAdapter(this,list);
//        listView.setAdapter(adapter);


        //搜索跳转
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String keywords = editText.getText().toString();
                //dao方法
                //dao.add(keywords);

                if (!TextUtils.isEmpty(keywords)) {
                    list1.add(keywords);
                    lastAdapter.notifyDataChanged();
                }

//                list = dao.select();
//                adapter = new MainAdapter(MainActivity.this,list);
//                listView.setAdapter(adapter);
                //跳转传值
                Intent intent = new Intent(MainActivity.this, LieBiaoActivity.class);
                intent.putExtra("keywords", keywords);
                startActivity(intent);
            }
        });
        //点击事件,流式布局
        last_tag.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                String key = lastAdapter.getItem(position);//获取点击项目的值
                //TODO 跳转到产品列表页面
                Intent intent = new Intent(MainActivity.this, LieBiaoActivity.class);
                intent.putExtra("key", key);
                startActivity(intent);
                return true;
            }
        });

        lishi1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                list1.clear();
                lastAdapter.notifyDataChanged();
            }
        });



        //流式布局
        for (int i = 0; i < mNAME.length; i++) {
            FluidLayout.LayoutParams params =
                    new FluidLayout.LayoutParams(
                            ViewGroup.LayoutParams.WRAP_CONTENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT
                    );
            params.setMargins(12, 12, 12, 12);
            TextView textView = new TextView(this);
            textView.setText(mNAME[i]);
            textView.setTextColor(Color.BLACK);
            textView.setBackgroundResource(R.drawable.flow_yangshi);

            fluidLayout.addView(textView, params);
        }

    }

    class KeyAdapter extends TagAdapter<String> {

        public KeyAdapter(List<String> datas) {
            super(datas);
        }

        @Override
        public View getView(FlowLayout parent, int position, String s) {
            TextView textView = new TextView(MainActivity.this);
            textView.setText(s);
            textView.setBackgroundResource(R.drawable.flow_yangshi);

            return textView;
        }
    }
}

activity_main

<LinearLayout
    android:id="@+id/linear"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    >
    <EditText
        android:id="@+id/souzhou"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="9"
        android:hint="搜索你要搜索的手机"
        />
    <Button
        android:id="@+id/sousuo"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:text="搜索"
        android:layout_weight="1"
        android:padding="10dp"
        />
</LinearLayout>

<TextView
    android:id="@+id/lishi"
    android:layout_width="match_parent"
    android:layout_height="31dp"
    android:text="最近搜索"
    android:textStyle="bold" />

<!--<ListView
    android:id="@+id/list_ite"
    android:layout_width="match_parent"
    android:layout_height="142dp">

</ListView>-->
<com.zhy.view.flowlayout.TagFlowLayout
    android:id="@+id/hot_tag"
    android:padding="16dp"
    app:max_select="1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

</com.zhy.view.flowlayout.TagFlowLayout>
<TextView
    android:id="@+id/sousuofaxian"
    android:layout_width="match_parent"
    android:layout_height="31dp"
    android:text="搜索发现"
    android:textStyle="bold" />
<com.fynn.fluidlayout.FluidLayout
    android:id="@+id/liushi"
    android:layout_width="match_parent"
    android:layout_height="125dp">

</com.fynn.fluidlayout.FluidLayout>

<Button
    android:id="@+id/btn_clear"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="清空历史记录"
    />
LieBiaoActivity

 

public class LieBiaoActivity extends AppCompatActivity implements IView {
    private XRecyclerView xRecyclerView;
    private EditText editText;
    private LieBiaoAdapter lieBiaoAdapter;
    //注入p层
    Presenter presenter;

    int page = 0 ;
    int sort = 0;
    String keywords;
    List<DataBean> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lie_biao);

        //初始化
        initview();

        presenter = new Presenter(this);

        keywords = getIntent().getStringExtra("keywords");
        editText.setText(keywords);
        presenter.getData(page,keywords,sort);
    }

    private void initview() {
        xRecyclerView = findViewById(R.id.xrecycler);
        editText = findViewById(R.id.edit_liebiao);
        xRecyclerView.setLoadingMoreEnabled(true);//加载更多
        xRecyclerView.setPullRefreshEnabled(true);//下拉刷新
        xRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page = 0 ;
                getData(page,keywords,sort);
            }
            @Override
            public void onLoadMore() {
                page++;
                getData(page,keywords,sort);
            }
        });

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        xRecyclerView.setLayoutManager(manager);
        //分割线
        xRecyclerView.addItemDecoration(new DividerItemDecoration(this, OrientationHelper.VERTICAL));



        //适配器
        lieBiaoAdapter = new LieBiaoAdapter(LieBiaoActivity.this);
        xRecyclerView.setAdapter(lieBiaoAdapter);


        //单击事件   适配器里的单击事件
        lieBiaoAdapter.setOnItemClickListener(new LieBiaoAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(DataBean dataBean) {
                Intent intent = new Intent(LieBiaoActivity.this,ShowShopActivity.class);

                int pid = dataBean.pid;
                String images = dataBean.images;
                intent.putExtra("images",images);
                intent.putExtra("pid",pid+"");
                startActivity(intent);
            }
        });
    }

    @Override
    public void ShowData(List<DataBean> data) {
            lieBiaoAdapter.addData(data);
    }


    //获取数据
    private void getData(int page, String keywords, int sort) {
        String url = Constants.HOST_URL;
        Ok.getOk().doGet(url + "searchProducts?keywords=" + keywords + "&page=" + page + "&sort=" + sort, new OkCallBack() {
            @Override
            public void success(String json) {
                Gson gson = new Gson();
                LieBiaoBean lieBiaoBean = gson.fromJson(json, LieBiaoBean.class);

                lieBiaoAdapter.addData(lieBiaoBean.data);
                xRecyclerView.refreshComplete();
                xRecyclerView.loadMoreComplete();
            }

            @Override
            public void failed(String json) {
                xRecyclerView.refreshComplete();
                xRecyclerView.loadMoreComplete();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.Destory();
    }
}

activity_lie_biao

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <EditText
        android:id="@+id/edit_liebiao"
        android:layout_width="match_parent"
        android:layout_height="40dp"

        />
</LinearLayout>
<com.jcodecraeer.xrecyclerview.XRecyclerView
    android:id="@+id/xrecycler"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</com.jcodecraeer.xrecyclerview.XRecyclerView>
ShowShopActivity
public class ShowShopActivity extends AppCompatActivity implements ShopView{
    private Banner banner;
    private Button button;
    public String pid;
    private List<String> list = new ArrayList<>();
    private ShopPresenter shopPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_shop);
        initview();

        shopPresenter= new ShopPresenter(this);

    }

    private void initview() {
        banner = findViewById(R.id.banner);
        button = findViewById(R.id.gouwu);

        banner.setImageLoader(new GlideImageLoader());
        String images = getIntent().getStringExtra("images");
        pid = getIntent().getStringExtra("pid");



        Log.i("TAG",pid+"");
        String split[] = images.split("\\|");

        for (int i = 0; i <split.length ; i++) {
            list.add(split[i]);
        }
        Toast.makeText(this,list+"",Toast.LENGTH_SHORT).show();
        banner.setImages(list);

        banner.start();



        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                shopPresenter.getCart(pid);
                Intent intent = new Intent(ShowShopActivity.this,GouWuActivity.class);
                startActivity(intent);
            }
        });
    }

    //展示
    @Override
    public void showCart(ShopData data) {
        Toast.makeText(this,data.msg,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showError(String error) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        shopPresenter.Destory();
    }
}

actvity_show_shop

<com.youth.banner.Banner
    android:id="@+id/banner"
    android:layout_width="match_parent"
    android:layout_height="260dp">

</com.youth.banner.Banner>

<LinearLayout
    android:id="@+id/line2"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentStart="true"
    android:orientation="horizontal">

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:text="供应商" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:text="店铺" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:text="关注" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:text="购物车" />

    <Button
        android:id="@+id/gouwu"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:gravity="center_vertical"
        android:text="加入购物车"
        android:textColor="#ffffff" />
</LinearLayout>
GouWuActivity
public class GouWuActivity extends AppCompatActivity implements ShopIView {
    private ExpandableListView ListView;
    //全选
    private ImageView img_check_all;
    //总价
    private TextView txt_total_price;
    private LinearLayout btn_check_all;

    //注入P层
    GouIPresent gouIPresent;
    //适配器
    GouWuAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gou_wu);
        //初始化
        initView();
        gouIPresent = new GouIPresent(this);
        gouIPresent.getCarts();
    }

    private void initView() {
        //获得组件
        ListView = findViewById(R.id.cartList);
        //TODO 设置二级列表 不能关闭
        ListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
                return  false;//返回true,表示不可点击
            }
        });
        //TODO 去掉默认箭头
        ListView.setGroupIndicator(null);

        //适配器
        adapter = new GouWuAdapter(this);
        ListView.setAdapter(adapter);

        //全选
        img_check_all = findViewById(R.id.img_check_all);
        //总价
        txt_total_price = findViewById(R.id.txt_total_price);
        btn_check_all = findViewById(R.id.btn_check_all);
        //选中
        btn_check_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //适配器选中 // TODO 全选反选
                if (adapter.isCheckAll()){
                    adapter.invertAll();//反选
                }else {
                    adapter.checkAll();//全选
                }
              //  adapter.sumPrice();
            }
        });


        adapter.setTxt_total_price(txt_total_price);
        adapter.setImg_check_all(img_check_all);

    }


    //适配器中添加数据
    @Override
    public void ShowData(List<DataBean> data) {
        adapter.addData(data);
        adapter.expandGroup(ListView);
        adapter.checkAll();

       // adapter.sumPrice();
    }

    @Override
    public void ShowError(String error) {
        Toast.makeText(this,error,Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        gouIPresent.Destory();
    }


}

activity_gou_wu

<RelativeLayout
    android:id="@+id/bottom_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentStart="true"
    android:padding="10dp">

    <LinearLayout
        android:id="@+id/btn_check_all"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/img_check_all"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_checked" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:text="全选" />

    </LinearLayout>

    <TextView
        android:id="@+id/txt_total_price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="84dp"
        android:text="合计:"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="16sp"
        android:textStyle="bold" />
</RelativeLayout>
<ExpandableListView
    android:id="@+id/cartList"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/bottom_layout"
    android:layout_alignParentTop="true"
    >

</ExpandableListView>
BasresenteP 接口
public interface BasePresent {
    void Destory();
}

App 照片处理

public class App extends Application{


    private Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        imageLoader();
    }

    private void imageLoader() {
        String path = Environment.getExternalStorageDirectory() + "Image";
        File cache = new File(path);
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .memoryCacheExtraOptions(480, 800)
                .diskCacheExtraOptions(480, 800, null)
                .threadPoolSize(3)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
                .memoryCacheSize(2 * 1024 * 1024)
                .memoryCacheSizePercentage(13)
                .diskCache(new UnlimitedDiskCache(cache))
                .diskCacheSize(50 * 1024 * 1024)
                .diskCacheFileCount(100)
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .writeDebugLogs()
                .build();
        ImageLoader.getInstance().init(config);
    }

    //图片处理
    public static DisplayImageOptions getOptions() {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.ic_launcher)
                .showImageForEmptyUri(R.mipmap.ic_launcher)
                .showImageOnFail(R.mipmap.ic_launcher)
                .resetViewBeforeLoading(false)
                .delayBeforeLoading(0)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
                .bitmapConfig(Bitmap.Config.ARGB_8888)
                .displayer(new RoundedBitmapDisplayer(300))
                .handler(new Handler())
                .build();


        return options;
    }
}

item_cart_product

 

<RelativeLayout
    android:id="@+id/layout_arrow"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="8dp">

    <TextView
        android:id="@+id/txt_arrow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:drawablePadding="8dp"
        android:drawableRight="@drawable/ic_arrow"
        android:text="逛一逛" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toLeftOf="@id/txt_arrow"
        android:text="优惠信息" />

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="323dp"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/layout_arrow">

    <ImageView
        android:id="@+id/img_select"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="82dp"
        android:src="@drawable/ic_checked" />

    <ImageView
        android:id="@+id/img_product"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="30dp"
        android:layout_marginTop="41dp"
        android:scaleType="centerCrop"
        android:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/txt_product_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:layout_alignTop="@id/img_product"
        android:layout_marginRight="20dp"
        android:layout_toRightOf="@id/img_product"
        android:singleLine="false"
        android:text="name"
        android:textSize="14sp" />

    <TextView
        android:id="@+id/txt_product_price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/txt_product_name"
        android:layout_alignTop="@+id/img_select"
        android:text="price"
        android:textColor="@color/colorAccent"
        android:textSize="14sp" />

    <com.meituan.tianlong.yuekaomoni.mvp.view.Adapter.gouwu.AddSumView
        android:id="@+id/add_sum"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_centerVertical="true"
        android:layout_marginEnd="30dp"></com.meituan.tianlong.yuekaomoni.mvp.view.Adapter.gouwu.AddSumView>


</RelativeLayout>

item_cart_seller

<ImageView
    android:id="@+id/img_select"
    android:src="@drawable/ic_checked"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/txt_seller_name"
    android:textSize="16sp"
    android:layout_marginLeft="10dp"
    android:textColor="@android:color/black"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

item_xlist

<ImageView
    android:id="@+id/imageView"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"

    android:layout_marginStart="51dp"
    android:layout_marginTop="54dp"
    app:srcCompat="@mipmap/ic_launcher" />

<TextView
    android:id="@+id/title_item"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@+id/imageView"
    android:layout_alignParentEnd="true"
    android:layout_alignTop="@+id/imageView"
    android:layout_marginEnd="167dp"
    android:text="title" />

<TextView
    android:id="@+id/price_item"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignStart="@+id/title_item"
    android:layout_marginTop="110dp"
    android:textColor="@color/colorAccent"
    android:textSize="18sp"
    android:text="price" />

layout_add_sum

<ImageView
    android:id="@+id/reduce"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_reduce"
    />
<TextView
    android:id="@+id/txt_sum"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="1"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:textStyle="bold"
    android:layout_margin="10dp"
    />
<ImageView
    android:id="@+id/add"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_add"
    />

mainlist

<TextView
    android:id="@+id/mainlist"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/flow_yangshi"
    />
Constants
public class Constants {
    public static final String HOST_URL = "http://www.zhaoapi.cn/product/";

    public static final String LIE_BIAO = HOST_URL+"searchProducts?keywords=手机&page=1&sort=0";

    public static final String GET_CARTS = HOST_URL+"product/getCarts";

    public static final String ADD_CARTS = HOST_URL+"product/addCart";

}
GouWuTask
public class GouWuTask implements GouWuCarts{

    @Override
    public void getCarts(String url, Map<String, String> map, OkCallBack okCallBack) {
        Ok.getOk().post(url,map,okCallBack);
    }
}
GouWuCarts 接口
public interface GouWuCarts {
        void getCarts(String url, Map<String,String> map , OkCallBack okCallBack);
}
Task
public class Task implements ITask{

    @Override
    public void getRecyclerView(String url, OkCallBack okCallBack) {
        Ok.getOk().doGet(url,okCallBack);
    }
}
ITask 接口
public interface ITask {
    void getRecyclerView(String url, OkCallBack okCallBack);
}
AddCartTask
public class AddCartTask implements AddCart{
    @Override
    public void addCart(String url, Map<String, String> map, OkCallBack okCallBack) {
        Ok.getOk().post(url,map,okCallBack);
    }
}
AddCart 接口
public interface AddCart {
    void addCart(String url, Map<String,String> map, OkCallBack okCallBack);
}
GouIPresent
public class GouIPresent implements GouWuIPresenter{
    //注入Model
    GouWuTask task;
    //注入view层
    ShopIView view;


    public GouIPresent(GouWuActivity activity) {
        this.task = new GouWuTask();
        this.view = activity;
    }

    @Override
    public void getCarts() {
        Map<String,String> map = new HashMap<>();
        map.put("uid","4243");
        map.put("token","94A2C256471982A75C170CAB844FE4FE");
        task.getCarts(Constants.GET_CARTS, map, new OkCallBack() {
            @Override
            public void success(String json) {
                Gson gson = new Gson();
                Data data = gson.fromJson(json, Data.class);
                if (TextUtils.equals(data.code,"0")){
                    view.ShowData(data.data);
                }else {
                    view.ShowError(data.msg);
                }
            }

            @Override
            public void failed(String json) {
                //TODO 当错时 展示信息
                view.ShowError(json);
            }
        });
    }

    @Override
    public void Destory() {
        view = null;
    }
}
GouWuIPresenter 接口
public interface GouWuIPresenter extends BasePresent{
    void getCarts();
}
IPresenter
public interface IPresenter extends BasePresent{
    public void getData(int page,String keywords,int sort);
}
Presenter
public class Presenter extends OkCallBack implements IPresenter{
    //注入model
    Task task;

    //注入view层
    IView view;

    public Presenter(LieBiaoActivity activity) {
        task = new Task();
        view = activity;
    }

    @Override
    public void getData(int page, String keywords, int sort) {

        task.getRecyclerView("https://www.zhaoapi.cn/product/searchProducts?keywords="+"手机"+"&page="+0+"&sort="+0,this);

    }

    @Override
    public void success(String json) {
        Gson gson = new Gson();
        LieBiaoBean lieBiaoBean = gson.fromJson(json, LieBiaoBean.class);
        view.ShowData(lieBiaoBean.data);
    }

    @Override
    public void failed(String json) {

    }

    @Override
    public void Destory() {
        view = null;
    }
}
IShopPresenter
public interface IShopPresenter extends BasePresent{
        void getCart(String pid);
}
ShopPresenter
public class ShopPresenter implements IShopPresenter{

    //注入model
    AddCartTask task;
    //注入view
    ShopView view;

    public ShopPresenter(ShowShopActivity  activity) {
        task = new AddCartTask();
        this.view = activity;
    }

    @Override
    public void getCart(String pid) {
        Map<String,String> map = new HashMap<>();

        map.put("uid","4243");
        map.put("pid",pid);
        task.addCart(Constants.ADD_CARTS, map, new OkCallBack() {
            @Override
            public void success(String json) {
                Gson gson = new Gson();
                ShopData shopData = gson.fromJson(json, ShopData.class);

                if (TextUtils.equals(shopData.code,"0")){
                    view.showCart(shopData);
                }else {
                    view.showError(shopData.msg);
                }
            }

            @Override
            public void failed(String json) {

            }
        });
    }

    @Override
    public void Destory() {

    }
}
ShopView 接口
public interface ShopView {
        void showCart(ShopData data);

        void showError(String error);
}
IView 接口
public interface IView{
        void ShowData(List<DataBean> data);
}
ShopIView 接口
public interface ShopIView {
    void ShowData(List<DataBean> data);

    void ShowError(String error);
}
MainAdapter 适配器
public class MainAdapter extends BaseAdapter {
    private Context context;
    private List<String> list;

    public MainAdapter(Context context, List<String> list) {
        this.context = context;
        this.list = list;
    }

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

    @Override
    public Object getItem(int i) {
        return null;
    }

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

    @Override
    public View getView(int i, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView==null){
            viewHolder = new ViewHolder();
            convertView = View.inflate(context, R.layout.mainlist,null);
            viewHolder.text01 = convertView.findViewById(R.id.mainlist);
            convertView.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.text01.setText(list.get(i));
        return convertView;
    }
    class ViewHolder{
        TextView text01;
    }
}
GlideImageLoader
public class GlideImageLoader extends ImageLoader{
    @Override
    public void displayImage(Context context, Object path, ImageView imageView) {
        Glide.with(context).load(path).into(imageView);
    }
}
LieBiaoAdapter
public  class LieBiaoAdapter extends XRecyclerView.Adapter<LieBiaoHolde> {
    List<DataBean> data;
    Context context;
    ImageLoader imageLoader;
    DisplayImageOptions options;
    private XRecyclerView xRecyclerView;
    private OnItemClickListener onItemClickListener;

    public LieBiaoAdapter(Context context) {
        this.data = new ArrayList<>();
        this.context = context;
        this.options = new DisplayImageOptions.Builder()
                .cacheOnDisk(true)
                .cacheInMemory(true)
                .build();
        imageLoader = ImageLoader.getInstance();
    }

    public void addData(List<DataBean> list){
        data.addAll(list);
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public LieBiaoHolde onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {


        View view= LayoutInflater.from(viewGroup.getContext())
                        .inflate(R.layout.item_xlist,viewGroup,false);
        LieBiaoHolde holde = new LieBiaoHolde(view);

        return holde;
    }

    @Override
    public void onBindViewHolder(@NonNull LieBiaoHolde lieBiaoHolde, int i) {
        final DataBean dataBean = data.get(i);

        lieBiaoHolde.title.setText(dataBean.title);
        lieBiaoHolde.price.setText("¥ "+dataBean.price+"");
        String url = dataBean.images.split("\\|")[0];
        imageLoader.displayImage(url,lieBiaoHolde.imageView,options);

        lieBiaoHolde.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onItemClickListener.onItemClick(dataBean);
            }
        });

    }

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



    /**
     * 1.以下是要在适配器中定义的单击事件
     *
     *
     * 定义 RecyclerView 选项单击事件的回调接口
     */
    public interface OnItemClickListener {
        void onItemClick(DataBean dataBean);
    }
    /**
     * 3.在适配器中声名 该接口 并提供setter方法
     */
    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    /**
     * 4 和 5  可写可不写
     * @param recyclerView
     */
    @Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

    @Override
    public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onDetachedFromRecyclerView(recyclerView);
    }
}
LieBiaoHolde
public class LieBiaoHolde extends XRecyclerView.ViewHolder{
    ImageView imageView;
    TextView title,price;
    public LieBiaoHolde(@NonNull View itemView) {
        super(itemView);
        imageView = itemView.findViewById(R.id.imageView);
        title = itemView.findViewById(R.id.title_item);
        price = itemView.findViewById(R.id.price_item);
    }
}
AddSumView
public class AddSumView extends LinearLayout {

    private Context context;

    private ImageView add;
    private ImageView reduce;
    private TextView sum;

    private int totalSum = 1 ;//记录商品数量
    private int limitSum = 5 ;//最多添加几件商品
    //定义点击事件
    private SumClickListener  listener;

    public void setSumClickListener(SumClickListener listener) {
        this.listener = listener;
    }


    public void setSum(int num) {
        totalSum = num;//设置初试数量
        this.sum.setText("" + num);
    }

    /**
     * 设置限购的数量
     *
     * @param limitSum
     */
    public void setLimitSum(int limitSum) {
        if (limitSum > 0) {
            this.limitSum = limitSum;
        } else {
            this.limitSum = 5;
        }
    }
    public AddSumView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        initview(context);
    }

    private void initview(Context context) {
        View view = View.inflate(context, R.layout.layout_add_sum_view,this);
        add  = view.findViewById(R.id.add);
        reduce = view.findViewById(R.id.reduce);
        sum = view.findViewById(R.id.txt_sum);
        //增加
        add.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                addClick();
            }
        });
        //减少
        reduce.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                reduceClick();
            }
        });

    }

    /**
     * 减少商品
     */
    public void reduceClick() {
        totalSum--;
        if (totalSum > 0) {
            sum.setText(totalSum + "");
        } else {
            totalSum = 1;//TODO
            Toast.makeText(context, "不能再减少了", Toast.LENGTH_SHORT).show();
            sum.setText(totalSum + "");
        }

        //回调事件
        if (listener != null) {
            listener.sumClick(totalSum);
        }
    }
    /**
     * private int totalSum = 1 ;//记录商品数量
     *private int limitSum = 5 ;//最多添加几件商品
     */
    /**
     * 增加数量
     */
    public void addClick() {
        totalSum ++ ;
        if (totalSum >= limitSum){
            totalSum = limitSum;
            Toast.makeText(context, "每人限购" + limitSum + "件", Toast.LENGTH_SHORT).show();
        }

        if (listener != null){
            listener.sumClick(totalSum);
        }

        sum.setText(totalSum+"");
    }

    /**
     *回调商品数量点击事件
     */
     interface SumClickListener {
        void sumClick(int psum);
    }
}
GouWuAdapter
public class GouWuAdapter extends BaseExpandableListAdapter {

    private List<DataBean> seller;//要请求数据
    private LayoutInflater inflater;//初始化视图
    private Context context;//上下文环境
    private TextView txt_total_price; //合计总价
    private ImageView img_check_all; //全选状态UI更新
    private boolean isCheckAll = false;//全选状态标记

    //图片
    private ImageLoader imageLoader;
    private DisplayImageOptions options;

    //构造器
    public GouWuAdapter(Context context) {
        //TODO 在这里初始化,避免空指针错误,下面在使用就不需要判断空指针
        this.seller = new ArrayList<>();
        this.inflater = LayoutInflater.from(context);
        this.context = context;
        options = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .build();
        imageLoader = ImageLoader.getInstance();

    }

    /**
     * 绑定顶部的总计价格控件
     * @param txt_total_price
     */
    public void setTxt_total_price(TextView txt_total_price) {
        this.txt_total_price = txt_total_price;
    }
    /**
     * 绑定全选按钮的控件
     * @param img_check_all
     */
    public void setImg_check_all(ImageView img_check_all) {
        this.img_check_all = img_check_all;
    }

    /**
     * 添加数据,这样写入数据,可以有效避免空指针操作
     * @param list
     */
    public void addData(List<DataBean> list){
        seller.addAll(list);//添加数据
        notifyDataSetChanged();//刷新数据
    }

    /**
     * 默认展开  默认全部展开
     * @param listView
     */
    public void expandGroup(ExpandableListView listView){
        for (int i = 0; i <getGroupCount() ; i++) {
            listView.expandGroup(i);
        }
    }


    public boolean isCheckAll() {
        return isCheckAll;
    }

    /**
     * 全选方案
     */
    public void checkAll(){
        isCheckAll  = true;//全选
        //遍历店铺
        for (DataBean seller: seller) {
            seller.isCheck = true;
            //遍历商品
            List<ListBean> list = seller.list;
            for (ListBean listBean : list) {
                if (isCheckAll){
                    //商品中的字段  0 为未选中 1 为选中
                    listBean.selected= 1;
                }
            }
            //更新UI
            updateSelectUI();
        }
    }
    /**
     * 反选方案
     */
    public void invertAll(){
        isCheckAll = false;//反选
        for (DataBean seller:seller) {//遍历商家
            seller.isCheck = false;//设置未选中
            for (ListBean listBean:seller.list ) {
                listBean.selected = 0;
            }
        }
        updateSelectUI();
    }
    /**
     * 刷新页面
     */
    public void updateSelectUI() {
        //全选按钮的处理
        if (isCheckAll){
            //图片的选中
            img_check_all.setImageResource(R.drawable.ic_checked);
        }else {
            //图片的未选中
            img_check_all.setImageResource(R.drawable.ic_uncheck);
        }
        //
        sumPrice();
        //刷新
        notifyDataSetChanged();
    }
    /**
     * 计算所选产品价格
     */
    public void sumPrice(){
        //计算总价
        int total = 0;

        for (DataBean dataBean: seller) {
            //选中的店铺
            if (dataBean.isCheck){
                for (ListBean listBean:dataBean.list) {
                    if (listBean.selected == 1){
                        //选中的产品的价格计算
                        //解析价格
                      //  int price =(int) Double.parseDouble(listBean.price);

                        total = total + listBean.price * listBean.num;
                    }
                }
            }
        }
        txt_total_price.setText("合计 ¥ " + total);
    }

    /**
     * 检查是否
     * @return
     */
    public boolean isQueryCheckAll() {
        int total = 0 ;//全部商品
        int checkNum= 0;//选中产品
        for (DataBean dataBean: seller) {//遍历商家
            total += dataBean.list.size();//统计数量
            if (dataBean.isCheck){//只需要遍历选中的商家
                for (ListBean listBean:dataBean.list) {//遍历产品
                    if (listBean.selected == 1){//如果选中产品
                        checkNum += 1;//选中产品数量+1
                    }
                }
            }
        }
        return checkNum == total;//比较。相等,即全选
    }

    /**
     * 获得商家总数据的长度
     * @return
     */
    @Override
    public int getGroupCount() {
        return seller.size();
    }

    /**
     * 获得商品总数据的长度
     * @param i
     * @return
     */
    @Override
    public int getChildrenCount(int i) {
        return seller.get(i).list.size();
    }

    /**
     * 获得商家类
     * @param i
     * @return
     */
    @Override
    public DataBean getGroup(int i) {
        return seller.get(i);
    }

    /**
     * 获得商品类
     * @param i
     * @param i1
     * @return
     */
    @Override
    public ListBean getChild(int i, int i1) {
        return seller.get(i).list.get(i1);
    }

    /**
     * 固定ID
     * @param i
     * @return
     */
    @Override
    public long getGroupId(int i) {
        DataBean group = getGroup(i);
        return group.sellerid;
    }

    @Override
    public long getChildId(int i, int i1) {
        ListBean child = getChild(i, i1);
        return child.sellerid;
    }

    /**
     * 允许固定ID
     * @return
     */
    @Override
    public boolean hasStableIds() {
        return true;
    }


    /**
     * 获得一级菜单的
     * @param i
     * @param b
     * @param view
     * @param viewGroup
     * @return
     */
    @Override
    public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
        DataBeanViewHolder holder;
        if (view == null){
            view = inflater.inflate(R.layout.item_cart_seller,viewGroup,false);
            holder = new DataBeanViewHolder(view);
            view.setTag(holder);

        }else {
            holder = (DataBeanViewHolder) view.getTag();
        }
        final DataBean dataBean = getGroup(i);
        holder.sellerName.setText(dataBean.sellerName);
        //选择
        if (dataBean.isCheck){
            holder.sellerCheck.setImageResource(R.drawable.ic_checked);
        }else {
            holder.sellerCheck.setImageResource(R.drawable.ic_uncheck);
        }
        //一级菜单复选框的单击事件
        holder.sellerCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //TODO 商家的单击事件
                clickSellerCheck(dataBean);
            }
        });
        return view;
    }
    //选择商家选中
    private void clickSellerCheck(DataBean dataBean) {

        List<ListBean> list = dataBean.list;
        if (dataBean.isCheck == true){
            dataBean.isCheck = false;
        }else {
            dataBean.isCheck = true;
        }

        //遍历商品
        for (ListBean listBean: list) {
            if (dataBean.isCheck){
                listBean.selected=1;
            }else {
                listBean.selected=0;
            }
        }
        isCheckAll = isQueryCheckAll();//查询是否为全部选中状态
        //计算价格
        sumPrice();
        //刷新UI
        updateSelectUI();
    }

    /**
     * 获得二级菜单  商品
     * @param i
     * @param i1
     * @param b
     * @param view
     * @param viewGroup
     * @return
     */
    @Override
    public View getChildView(final int i, int i1, boolean b, View view, ViewGroup viewGroup) {
        ListBeanViewHolder listholder;
        if (view == null){
            view = inflater.inflate(R.layout.item_cart_product,viewGroup,false);
            listholder = new ListBeanViewHolder(view);
            view.setTag(listholder);
        }else {
            listholder = (ListBeanViewHolder) view.getTag();
        }
        final ListBean child = getChild(i, i1);

        listholder.listBeanName.setText(child.title);
        listholder.listBeanPrice.setText("¥"+child.price);

        listholder.addSumView.setSum(child.num);


        String url = child.images.split("\\|")[0];
        imageLoader.displayImage(url,listholder.listBeanImages,options);

        if (child.selected ==1){
            listholder.listCheck.setImageResource(R.drawable.ic_checked);
        }else {
            listholder.listCheck.setImageResource(R.drawable.ic_uncheck);
        }

        //设置选中监听
        listholder.listCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               //获取商家
                DataBean dataBean = getGroup(i);
                clickDataBeanCheck(dataBean,child);
            }
        });

        listholder.addSumView.setSumClickListener(new AddSumView.SumClickListener() {
            @Override
            public void sumClick(int psum) {
                child.num = psum;
                sumPrice();
            }
        });

        return view;
    }

    private void clickDataBeanCheck(DataBean dataBean, ListBean child) {
        //全未选中,选择中产品的时候商家也选中,全选按钮是未选中状态
        //全选中,只要有一个未选,影响自己,和全选按钮
        if (child.selected == 1) {
            child.selected = 0;//产品未选中
            //TODO 当多个产品需要处理
            int selectedNum = 0;
            for (ListBean ptemp : dataBean.list) {//遍历产品
                if (ptemp.selected == 1) {
                    selectedNum += 1;//选中增加1
                }
            }
            if (selectedNum > 0) {//产品只要一个选中,商家就是选中状态
                dataBean.isCheck = true;
            } else {
                dataBean.isCheck = false;
            }

        } else {
            child.selected = 1;//产品选中
            dataBean.isCheck = true;//有一个产品选中,商家即为选中状态
        }

        isCheckAll = isQueryCheckAll();//查询是否为全部选中状态

        updateSelectUI();//更新UI
    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return false;
    }

    /**
     *
     * @param listBean  产品
     * @param spos       位置
     */
    private void clickListBeanCheck(ListBean listBean , int spos){
        if (listBean.selected == 1){
            listBean.selected =0;
        }else {
            listBean.selected =1;
        }

        //获取当前商品的店铺信息
        DataBean dataBean = getGroup(spos);
        //统计产品选中数量
        int sum = 0 ;

        for (ListBean list: dataBean.list) {
            if (list.selected == 1){//判断当前店铺有无选中产品
                sum   = +1;//统计数量
            }
        }
        if (sum == 0){
            dataBean.isCheck =false ;
        }else {
            dataBean.isCheck = true;
        }
        //计算价格
        sumPrice();

        notifyDataSetChanged();


    }
    /**
     * 商家
     */
    static class DataBeanViewHolder {
        TextView sellerName;//商家名称
        ImageView sellerCheck;//选中按钮

        public DataBeanViewHolder(View view){
            sellerName = view.findViewById(R.id.txt_seller_name);
            sellerCheck = view.findViewById(R.id.img_select);
        }
    }

    /**
     * 商品
     */
    static class ListBeanViewHolder {
        TextView listBeanName;
        TextView listBeanPrice;
        ImageView listCheck;
        ImageView listBeanImages;
        AddSumView addSumView;

        public ListBeanViewHolder(View view) {
            listBeanName = view.findViewById(R.id.txt_product_name);
            listBeanPrice=view.findViewById(R.id.txt_product_price);
            listCheck = view.findViewById(R.id.img_select);
            listBeanImages = view.findViewById(R.id.img_product);
            addSumView = view.findViewById(R.id.add_sum);
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值