所需依赖
/*Picasso依赖*/
implementation 'com.squareup.picasso:picasso:2.3.2'
/*banner轮播图 依赖*/
implementation 'com.youth.banner:banner:1.4.9'
/*gson解析*/
implementation 'com.google.code.gson:gson:2.2.4'
/*okhttp网络请求*/
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
/*recyclerview展示*/
implementation 'com.android.support:recyclerview-v7:28.0.0'
/*xrecyclerview展示*/
implementation 'com.jcodecraeer:xrecyclerview:1.2.0'
/*glide图片工具*/
implementation 'com.github.bumptech.glide:glide:4.8.0'
IView
public interface IVew {
Context context();
}
DataCall–继承IView
public interface DataCall extends IVew {
void ShowSuccess(GoodsBean goodsBean);//商品列表数据
void ShowShopSuccess(List<Shop.DataBean> dataBean);//购物车数据
void ShowError(String error);//失败
}
GoodsModel–传入page,name
public void showGoods(int page, String name, final MainmodelCallback mainmodelCallback) {
HttpUtils httpUtils = HttpUtils.getHttpUtils();
String url = "http://www.zhaoapi.cn/product/searchProducts?keywords=" + name + "&page=" + page;
httpUtils.doGet(url, new HttpUtils.IOKhttpUtilsCallback() {
@Override
public void onFailure(String error) {
if (mainmodelCallback != null) {
mainmodelCallback.getFaid(error);
}
}
@Override
public void onResponse(String json) {
GoodsBean goodsBean = new Gson().fromJson(json, GoodsBean.class);
if (goodsBean.getCode().equals("0")) {
if (mainmodelCallback != null) {
mainmodelCallback.getSuccess(goodsBean);
}
} else {
if (mainmodelCallback != null) {
mainmodelCallback.getFaid("请求失败");
}
}
}
});
}
public interface MainmodelCallback {
void getSuccess(GoodsBean goodsBean);
void getFaid(String error);
}
ShopModel–传入接口
public void showGoods(String url, final MainmodelCallback mainmodelCallback) {
HttpUtils httpUtils = HttpUtils.getHttpUtils();
httpUtils.doGet(url, new HttpUtils.IOKhttpUtilsCallback() {
@Override
public void onFailure(String error) {
if (mainmodelCallback != null) {
mainmodelCallback.getFaid(error);
}
}
@Override
public void onResponse(String json) {
if (json != null && !json.equals("")) {
if (mainmodelCallback != null) {
Shop shop = new Gson().fromJson(json, Shop.class);
mainmodelCallback.getSuccess(shop.getData());
}
} else {
if (mainmodelCallback != null) {
mainmodelCallback.getFaid("请求失败");
}
}
}
});
}
public interface MainmodelCallback {
void getSuccess(List<Shop.DataBean> dataBean);
void getFaid(String error);
}
BasePresenter
public abstract class BasePresenter<V extends IVew> {
protected V view;
public BasePresenter(V view) {
this.view = view;
initModel();
}
protected abstract void initModel();
public void onDestroy() {
view = null;
}
}
GoodsPresenter
public class GoodsPresenter extends BasePresenter<DataCall> {
private GoodsModel goodsModel;
public GoodsPresenter(DataCall view) {
super(view);
}
@Override
protected void initModel() {
goodsModel = new GoodsModel();
}
public void showGoods(int page, String name) {
goodsModel.showGoods(page, name, new GoodsModel.MainmodelCallback() {
@Override
public void getSuccess(GoodsBean goodsBean) {
view.ShowSuccess(goodsBean);
}
@Override
public void getFaid(String error) {
view.ShowError(error);
}
});
}
}
ShopPresenter
public class ShopPresenter extends BasePresenter<DataCall> {
private ShopModel shopModel;
public ShopPresenter(DataCall view) {
super(view);
}
@Override
protected void initModel() {
shopModel = new ShopModel();
}
public void showShop(String url) {
shopModel.showGoods(url, new ShopModel.MainmodelCallback() {
@Override
public void getSuccess(List<Shop.DataBean> dataBean) {
view.ShowShopSuccess(dataBean);
}
@Override
public void getFaid(String error) {
view.ShowError(error);
}
});
}
}
HttpUtils
public class HttpUtils {
public static HttpUtils httpUtils;
private final Handler handler;
private final OkHttpClient HttpClient;
private HttpUtils() {
//主线程Handler
handler = new Handler(Looper.getMainLooper());
HttpClient = new OkHttpClient.Builder()
.readTimeout(5000, TimeUnit.MILLISECONDS)
.writeTimeout(5000, TimeUnit.MILLISECONDS)
.connectTimeout(5000, TimeUnit.MILLISECONDS)
.connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS))
.build();
}
public static HttpUtils getHttpUtils() {
if (httpUtils == null) {
synchronized (HttpUtils.class) {
if (httpUtils == null) {
return httpUtils = new HttpUtils();
}
}
}
return httpUtils;
}
//异步get
public void doGet(String url, final IOKhttpUtilsCallback ioKhttpUtilsCallback) {
Request request = new Request.Builder().get().url(url).build();
Call call = HttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
if (ioKhttpUtilsCallback != null) {
handler.post(new Runnable() {
@Override
public void run() {
ioKhttpUtilsCallback.onFailure(e.getMessage());
}
});
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response != null && response.isSuccessful()) {
final String json = response.body().string();
if (ioKhttpUtilsCallback != null) {
//切换到主线程
handler.post(new Runnable() {
@Override
public void run() {
ioKhttpUtilsCallback.onResponse(json);
}
});
}
} else {
if (ioKhttpUtilsCallback != null) {
//切换到主线程
handler.post(new Runnable() {
@Override
public void run() {
ioKhttpUtilsCallback.onFailure("网络异常");
}
});
}
}
}
});
}
//异步post
public void doPost(String url, Map<String, String> map, final IOKhttpUtilsCallback ioKhttpUtilsCallback) {
FormBody.Builder builder = new FormBody.Builder();
for (Map.Entry<String, String> entry : map.entrySet()) {
builder.add(entry.getKey(), entry.getValue());
}
FormBody formBody = builder.build();
Request request = new Request.Builder()
.post(formBody)
.url(url)
.build();
Call call = HttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
if (ioKhttpUtilsCallback != null) {
//切换到主线程
handler.post(new Runnable() {
@Override
public void run() {
ioKhttpUtilsCallback.onFailure(e.getMessage());
}
});
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response != null && response.isSuccessful()) {
final String json = response.body().string();
if (ioKhttpUtilsCallback != null) {
//切换到主线程
handler.post(new Runnable() {
@Override
public void run() {
ioKhttpUtilsCallback.onResponse(json);
}
});
}
} else {
if (ioKhttpUtilsCallback != null) {
//切换到主线程
handler.post(new Runnable() {
@Override
public void run() {
ioKhttpUtilsCallback.onFailure("网络异常");
}
});
}
}
}
});
}
//接口回调
public interface IOKhttpUtilsCallback {
void onFailure(String error);
void onResponse(String json);
}
}
MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener,DataCall {
private ImageView mBtnBack;
private ImageView mBtnMenu;
private XRecyclerView mXrecy;
private int type = 1;
private GoodsAdapter adapter;
private SearchView mSea;
private GoodsPresenter presenter;
private List<GoodsBean.DataBean> list;
private int page = 1;
private String sname = "手机";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
initView();
//数据获取
initData();
//刷新加载
initRefresh();
mSea = (SearchView) findViewById(R.id.sea);
mSea.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
presenter.showGoods(1, s);
sname = s;
return false;
}
});
}
private void initRefresh() {
mXrecy.setLoadingListener(new XRecyclerView.LoadingListener() {
@Override
public void onRefresh() {
//更新UI
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
page = 1;
presenter.showGoods(page, sname);
mXrecy.refreshComplete();
Toast.makeText(MainActivity.this, "刷新完成", Toast.LENGTH_SHORT).show();
}
}, 2000);
}
@Override
public void onLoadMore() {
//更新UI
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
page++;
presenter.showGoods(page, sname);
mXrecy.loadMoreComplete();
Toast.makeText(MainActivity.this, "加载完成", Toast.LENGTH_SHORT).show();
}
}, 2000);
}
});
}
private void initData() {
presenter = new GoodsPresenter(this);
presenter.showGoods(1, "笔记本");
mBtnMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (type == 1) {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mXrecy.setLayoutManager(linearLayoutManager);
adapter.notifyDataSetChanged();
type = 2;
} else {
GridLayoutManager gridLayoutManager = new GridLayoutManager(MainActivity.this, 2);
mXrecy.setLayoutManager(gridLayoutManager);
adapter.notifyDataSetChanged();
type = 1;
}
}
});
}
private void initView() {
mBtnBack = (ImageView) findViewById(R.id.btn_back);
mBtnMenu = (ImageView) findViewById(R.id.btn_menu);
mBtnMenu.setOnClickListener(this);
mXrecy = (XRecyclerView) findViewById(R.id.xrecy);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
default:
break;
case R.id.btn_menu:
break;
}
}
@Override
public void ShowSuccess(GoodsBean goodsBean) {
list = goodsBean.getData();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mXrecy.setLayoutManager(linearLayoutManager);
adapter = new GoodsAdapter(list, context());
mXrecy.setAdapter(adapter);
}
@Override
public void ShowShopSuccess(List<Shop.DataBean> dataBeans) {
}
@Override
public void ShowError(String error) {
Toast.makeText(this, "失败——————" + error, Toast.LENGTH_SHORT).show();
}
@Override
public Context context() {
return this;
}
@Override
protected void onDestroy() {
super.onDestroy();
presenter.onDestroy();
}
}
GoodsAdapter
public class GoodsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<GoodsBean.DataBean> list;
private Context context;
public GoodsAdapter(List<GoodsBean.DataBean> list, Context context) {
this.list = list;
this.context = context;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.itemlayout, viewGroup, false);
return (new ViewHolder(view));
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, final int position) {
((ViewHolder) viewHolder).item_dec.setText(list.get(position).getTitle());
((ViewHolder) viewHolder).item_price.setText(list.get(position).getPrice() + "");
String images = list.get(position).getImages();
String imageurl = "http" + images.substring(5);
String[] split = imageurl.split("\\|");
if (split.length > 0) {
Glide.with(context).load(split[0]).into(((ViewHolder) viewHolder).item_img);
// Glide.with(context).load(ii).into(((ViewHolder) viewHolder).item_img);
}
viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
ObjectAnimator alpha = ObjectAnimator.ofFloat(view, "alpha", 1f, 0f, 1f);
alpha.setDuration(5000);
alpha.start();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("删除");
builder.setMessage("确认删除吗");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
list.remove(position);
notifyDataSetChanged();
}
});
builder.setNegativeButton("取消", null);
builder.show();
return true;
}
});
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(context, DataActivity.class);
intent.putExtra("aaa", list.get(position).getTitle());
intent.putExtra("bbb", list.get(position).getBargainPrice());
intent.putExtra("eee", list.get(position).getImages());
context.startActivity(intent);
Toast.makeText(context, "点击了" + position, Toast.LENGTH_LONG).show();
}
});
}
@Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView item_dec, item_price;
private ImageView item_img;
public ViewHolder(View itemView) {
super(itemView);
item_img = itemView.findViewById(R.id.img_icon);
item_dec = itemView.findViewById(R.id.txt_name);
item_price = itemView.findViewById(R.id.txt_price);
}
}
}
GlideApp
public class GildeApplication extends ImageLoader {
@Override
public void displayImage(Context context, Object path, ImageView imageView) {
//初始化Glid包
Glide.with(context).load(path).into(imageView);
}
}
DataActivity
public class DataActivity extends AppCompatActivity {
private Banner mMyBanner;
private String[] split;
private TextView mText;
private TextView mText2;
private RadioButton mBtnCar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data);
//初始化控件
initView();
//ok网络请求
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url("http://api.tianapi.com/meinv/?key=2a0024d1f7f558e09936f697580f1643&num=5")
.build();
Call call = okHttpClient.newCall(request);
//用okHttp里面的call对象打点调用 异步请求数据的抽象方法
call.enqueue(new Callback() {
//建个集合 用来存放图片的url地址
private List<String> picUrlList;
//此集合是bean解析过来的集合
private List<IconBean.NewslistBean> list;
@Override
public void onFailure(Call call, IOException e) {
//访问网络失败的方法(自动生成的)
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//访问网络成功的方法(自动生成的)
//这是bena里边的数据
String json = response.body().string();
//开始Gson解析
Gson gson = new Gson();
IconBean myBean = gson.fromJson(json, IconBean.class);
//拿到bean类里的集合
list = myBean.getNewslist();
//设此局此集合专门用来存放图片url地址的
picUrlList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
//循环吧图片地址添加到String泛型的集合里
picUrlList.add(list.get(i).getPicUrl());
}
//子线程不能更新UI
//所以【必须】开启返回主线程的方法
runOnUiThread(new Runnable() {
@Override
public void run() {
mMyBanner.setImages(picUrlList).setImageLoader(new GildeApplication()).start();
}
});
}
});
mBtnCar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//跳转购物车
startActivity(new Intent(DataActivity.this, ShowActivity.class));
}
});
}
private void initView() {
mMyBanner = findViewById(R.id.myBanner);
mText = findViewById(R.id.text);
mText2 = findViewById(R.id.text2);
mBtnCar = findViewById(R.id.btn_car);
Intent intent = getIntent();
String images = intent.getStringExtra("eee");
String aaa = intent.getStringExtra("aaa");
mText.setText(aaa);
String bbb = intent.getStringExtra("bbb");
mText2.setText(bbb);
}
}
自定义View–加减
public class MyAddSub extends LinearLayout implements View.OnClickListener {
private TextView addText;
private TextView subText;
private TextView numText;
private int number = 1;
public MyAddSub(Context context) {
this(context, null);
}
public MyAddSub(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyAddSub(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
View view = inflate(context, R.layout.add_sub_item, this);
addText = view.findViewById(R.id.add_text);
subText = view.findViewById(R.id.sub_text);
numText = view.findViewById(R.id.num_text);
addText.setOnClickListener(this);
subText.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.add_text:
++number;
numText.setText(number + "");
if (mOnNumberChangeInterface != null) {
mOnNumberChangeInterface.onNumberChang(number);
}
break;
case R.id.sub_text:
//判断如果数字比1大就减,比1小就吐司
if (number > 1) {
--number;
numText.setText(number + "");
if (mOnNumberChangeInterface != null) {
mOnNumberChangeInterface.onNumberChang(number);
}
} else {
Toast.makeText(getContext(), "不能再少了", Toast.LENGTH_SHORT).show();
}
break;
}
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
numText.setText(number + "");
}
//创建接口
public interface OnNumberChangeInterface {
void onNumberChang(int num);
}
//声明接口名
private OnNumberChangeInterface mOnNumberChangeInterface;
//暴露方法
public void setOnNumberChangeInterface(OnNumberChangeInterface onNumberChangeInterface) {
mOnNumberChangeInterface = onNumberChangeInterface;
}
}
购物车布局
<ExpandableListView
android:id="@+id/ex_listView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="10" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
<CheckBox
android:id="@+id/all_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="全选" />
<TextView
android:id="@+id/all_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="总价:¥0.00"
android:textSize="18sp" />
<Button
android:id="@+id/jiesuan_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="结算" />
</LinearLayout>
加减布局-----add_sub_item
<TextView
android:id="@+id/sub_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="-"
android:textSize="20sp" />
<TextView
android:id="@+id/num_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="1"
android:textSize="20sp" />
<TextView
android:id="@+id/add_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="+"
android:textSize="20sp" />
商品布局-----child_item
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="@+id/child_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" />
<ImageView
android:id="@+id/child_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:padding="10dp"
android:src="@mipmap/ic_launcher" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="@+id/child_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="15dp"
android:text="jhsjhdsk"
android:textSize="17sp" />
<TextView
android:id="@+id/child_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="¥0.0" />
</LinearLayout>
****************注意注意**************
<com.example.lg.lxyk02_1218.MyAddSub
android:id="@+id/add_sub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center_vertical"></com.example.lg.lxyk02_1218.MyAddSub>
商家布局—parent_item
<CheckBox
android:id="@+id/box_parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<TextView
android:id="@+id/text_parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="商家"
android:textSize="20sp" />
ShopAdapter
public class ShopAdapter extends BaseExpandableListAdapter {
private List<Shop.DataBean> shopData;
private double price;
private int num;
public ShopAdapter(List<Shop.DataBean> shopData) {
this.shopData = shopData;
}
//1.有多少按钮
@Override
public int getGroupCount() {
return shopData.size();
}
//2.一个组里有多少子条目
@Override
public int getChildrenCount(int groupPosition) {
return shopData.get(groupPosition).getList().size();
}
////////P.组布局////////
@Override
public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
//P1.获取组的下标
Shop.DataBean dataBean = shopData.get(groupPosition);
ParentHolder parentHolder;
if (convertView == null) {
convertView = View.inflate(parent.getContext(), R.layout.parent_item, null);
parentHolder = new ParentHolder(convertView);
convertView.setTag(parentHolder);
} else {
parentHolder = (ParentHolder) convertView.getTag();
}
//P2.获取商家名称
parentHolder.textParent.setText(dataBean.getSellerName());
//P3.根据当前商家的所有商品,确定checkbox是否选中
boolean parentAllSelect = isParentAllSelect(groupPosition);
//P4.1根据boolean判断是否选中
parentHolder.boxParent.setChecked(parentAllSelect);
//P5.设置点击checkbox的点击事件,接口回调
parentHolder.boxParent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mOnCartListChangeListener != null) {
mOnCartListChangeListener.onParentCheckedChange(groupPosition);
}
}
});
return convertView;
}
////////////C.子布局///////////
@Override
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
Shop.DataBean dataBean = shopData.get(groupPosition);
List<Shop.DataBean.ListBean> list = dataBean.getList();
//C1.拿到list集合里具体商品
Shop.DataBean.ListBean listBean = list.get(childPosition);
ChildHolder childHolder;
if (convertView == null) {
convertView = View.inflate(parent.getContext(), R.layout.child_item, null);
// convertView = View.inflate(parent.getContext(), R.layout.child_item, null);
childHolder = new ChildHolder(convertView);
convertView.setTag(childHolder);
} else {
childHolder = (ChildHolder) convertView.getTag();
}
//C2.截取图片picasso
String images = listBean.getImages();
String[] strings = images.split("!");
Picasso.with(parent.getContext()).load(strings[0]).into(childHolder.imageChild);
//C.获取商品名称
childHolder.childText.setText(listBean.getTitle());
//C.单价
childHolder.childPrice.setText(listBean.getPrice() + "");
//C.设置子条目复选框是否选中
childHolder.boxChild.setChecked(listBean.getSelected() == 1);
//C.设置加减器内部数量
childHolder.addSub.setNumber(listBean.getNum());
//C3.设置商品checkbox的点击事件,接口回调
childHolder.boxChild.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mOnCartListChangeListener != null) {
mOnCartListChangeListener.onChildCheckedChange(groupPosition, childPosition);
}
}
});
//C4.设置加减器的点击事件,接口回调
childHolder.addSub.setOnNumberChangeInterface(new MyAddSub.OnNumberChangeInterface() {
@Override
public void onNumberChang(int num) {
if (mOnCartListChangeListener != null) {
mOnCartListChangeListener.onAddSubNumberChange(groupPosition, childPosition, num);
}
}
});
return convertView;
}
//--------判断当前商品是否被选中--------
public boolean isParentAllSelect(int groupPosition) {
//拿到组的数据
Shop.DataBean dataBean = shopData.get(groupPosition);
//拿到商家所有商品,集合
List<Shop.DataBean.ListBean> list = dataBean.getList();
for (int i = 0; i < list.size(); i++) {
//判断这个组所有商品是否被选中,如有一个未选中就都不选中
if (list.get(i).getSelected() == 0) {
return false;
}
}
return true;
}
//------底部全选按钮逻辑判断------
public boolean isAllSelected() {
for (int i = 0; i < shopData.size(); i++) {
Shop.DataBean dataBean = shopData.get(i);
List<Shop.DataBean.ListBean> list = dataBean.getList();
for (int j = 0; j < list.size(); j++) {
//判断组的商品是否被选中
if (list.get(j).getSelected() == 0) {
return false;
}
}
}
return true;
}
//-----计算商品总数量-----
public int TotalNumber() {
int totalNumber = 0;
for (int i = 0; i < shopData.size(); i++) {
Shop.DataBean dataBean = shopData.get(i);
List<Shop.DataBean.ListBean> list = dataBean.getList();
for (int j = 0; j < list.size(); j++) {
//商品数量,选中的
if (list.get(j).getSelected() == 1) {
//拿到商品的数量
int num = list.get(j).getNum();
totalNumber += num;
}
}
}
return totalNumber;
}
//-------计算商品总价格-------
public float TotalPrice() {
float totalPrice = 0;
for (int i = 0; i < shopData.size(); i++) {
Shop.DataBean dataBean = shopData.get(i);
List<Shop.DataBean.ListBean> list = dataBean.getList();
for (int j = 0; j < list.size(); j++) {
//商品价格,选中的
if (list.get(j).getSelected() == 1) {
//拿到商品数量
price = list.get(j).getPrice();
num = (int) (list.get(j).getNum() * price);
totalPrice += num;
}
}
}
// totalPrice -= price;
return totalPrice;
}
//--------根据选择,更改选框里状态------
public void changeSellerAllProduct(int groupPosition, boolean isSelected) {
Shop.DataBean dataBean = shopData.get(groupPosition);
List<Shop.DataBean.ListBean> list = dataBean.getList();
for (int i = 0; i < list.size(); i++) {
Shop.DataBean.ListBean listBean = list.get(i);
listBean.setSelected(isSelected ? 1 : 0);
}
}
//---------当子条目选中,更新组选框的状态-------
public void changeChild(int groupPosition, int childPosition) {
Shop.DataBean dataBean = shopData.get(groupPosition);
List<Shop.DataBean.ListBean> list = dataBean.getList();
Shop.DataBean.ListBean listBean = list.get(childPosition);
listBean.setSelected(listBean.getSelected() == 0 ? 1 : 0);
}
//---------当最底部全选框选中,更新所有选框的状态
public void changAllCheckBox(boolean selected) {
for (int i = 0; i < shopData.size(); i++) {
Shop.DataBean dataBean = shopData.get(i);
List<Shop.DataBean.ListBean> list = dataBean.getList();
for (int j = 0; j < list.size(); j++) {
list.get(j).setSelected(selected ? 1 : 0);
}
}
}
//----------当加减器被点击时,改变商品数量--------
public void changProductNumber(int groupPosition, int childPosition, int number) {
Shop.DataBean dataBean = shopData.get(groupPosition);
List<Shop.DataBean.ListBean> list = dataBean.getList();
Shop.DataBean.ListBean listBean = list.get(childPosition);
listBean.setNum(number);
}
//==============Viewhodler============
//组的Viewholder
public static class ParentHolder {
private final CheckBox boxParent;
private final TextView textParent;
public ParentHolder(View rootView) {
boxParent = rootView.findViewById(R.id.box_parent);
textParent = rootView.findViewById(R.id.text_parent);
}
}
public static class ChildHolder {
private final CheckBox boxChild;
private final ImageView imageChild;
private final TextView childText;
private final TextView childPrice;
private final MyAddSub addSub;
public ChildHolder(View rootView) {
boxChild = rootView.findViewById(R.id.child_box);
imageChild = rootView.findViewById(R.id.child_image);
childText = rootView.findViewById(R.id.child_text);
childPrice = rootView.findViewById(R.id.child_price);
addSub = rootView.findViewById(R.id.add_sub);
}
}
//=============创建接口===========
public interface onCartListChangeListener {
/*当组的checkbox点击时回调*/
void onParentCheckedChange(int groupPosition);
/*当点击子条目商品的checkbox回调*/
void onChildCheckedChange(int groupPosition, int childPosition);
/*当点击加减按钮的回调*/
void onAddSubNumberChange(int groupPosition, int childPosition, int number);
}
private onCartListChangeListener mOnCartListChangeListener;
public void setOnCartListChangeListener(onCartListChangeListener onCartListChangeListener) {
mOnCartListChangeListener = onCartListChangeListener;
}
//不管这些
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
@Override
public Object getGroup(int groupPosition) {
return null;
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return null;
}
@Override
public long getGroupId(int groupPosition) {
return 0;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
@Override
public boolean hasStableIds() {
return false;
}
}
ShopActivity
public class ShowActivity extends AppCompatActivity implements View.OnClickListener, DataCall {
private ExpandableListView ex_listView;
private CheckBox all_box;
private TextView all_price;
private Button jiesuan_btn;
private ShopAdapter shopAdapter;
private String url = "http://www.zhaoapi.cn/product/getCarts?uid=71";
private ShopPresenter shopPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
//A.获取控件
initView();
//B.获取数据
shopPresenter = new ShopPresenter(this);
shopPresenter.showShop(url);
}
//-------底部全选框的点击事件--------
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.all_box:
boolean allSelected = shopAdapter.isAllSelected();
shopAdapter.changAllCheckBox(!allSelected);
shopAdapter.notifyDataSetChanged();
//刷新底部的数据显示
refreshAllShop();
break;
}
}
//A.初始化控件
private void initView() {
ex_listView = findViewById(R.id.ex_listView);
all_box = findViewById(R.id.all_box);
all_price = findViewById(R.id.all_price);
jiesuan_btn = findViewById(R.id.jiesuan_btn);
all_box.setOnClickListener(this);
}
//--------刷新底部---------
private void refreshAllShop() {
//判断是否所有商品都被选中
boolean allSelected = shopAdapter.isAllSelected();
//设置给checkbox
all_box.setChecked(allSelected);
//计算总计
float price = shopAdapter.TotalPrice();
all_price.setText("总计" + price);
//计算数量
int number = shopAdapter.TotalNumber();
jiesuan_btn.setText("去结算(" + number + ")");
}
@Override
public void ShowSuccess(GoodsBean goodsBean) {
}
@Override
public void ShowShopSuccess(List<Shop.DataBean> dataBeans) {
//B1.获取适配器
shopAdapter = new ShopAdapter(dataBeans);
//B2.对适配器设置监听(加减器,组,子条目复选框改变)
shopAdapter.setOnCartListChangeListener(new ShopAdapter.onCartListChangeListener() {
//------B2.1.组的复选框被点击------
@Override
public void onParentCheckedChange(int groupPosition) {
boolean parentAllSelect = shopAdapter.isParentAllSelect(groupPosition);
shopAdapter.changeSellerAllProduct(groupPosition, !parentAllSelect);
shopAdapter.notifyDataSetChanged();
//刷新底部
refreshAllShop();
}
//-------B2.2.子条目的复选框被点击-------
@Override
public void onChildCheckedChange(int groupPosition, int childPosition) {
shopAdapter.changeChild(groupPosition, childPosition);
shopAdapter.notifyDataSetChanged();
refreshAllShop();
}
//-------B2.3.加减器被点击------
@Override
public void onAddSubNumberChange(int groupPosition, int childPosition, int number) {
shopAdapter.changProductNumber(groupPosition, childPosition, number);
shopAdapter.notifyDataSetChanged();
refreshAllShop();
}
});
//B3.设置adapter对象
ex_listView.setAdapter(shopAdapter);
//B4.展开二级列表
for (int i = 0; i < dataBeans.size(); i++) {
ex_listView.expandGroup(i);
}
}
@Override
public void ShowError(String error) {
Toast.makeText(ShowActivity.this, "66666 +." + error, Toast.LENGTH_SHORT).show();
}
@Override
public Context context() {
return this;
}
}