项目需要的依赖Gson,okhttp,glide
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
implementation 'com.github.bumptech.glide:glide:4.8.0'
网络权限
<uses-permission android:name="android.permission.INTERNET"/>
Activity里面的代码
public class MainActivity extends AppCompatActivity implements DataCall<List<Shop>>,CartAdapter.TotalPriceListener {
private TextView mSumPrice;
private CheckBox mCheckAll;
private CartPresenter cartPresenter = new CartPresenter(this);
private ExpandableListView mGoodsList;
private CartAdapter mCartAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSumPrice = findViewById(R.id.goods_sum_price);
mCheckAll = findViewById(R.id.check_all);
mGoodsList = findViewById(R.id.list_cart);
mCartAdapter = new CartAdapter(this);
mGoodsList.setAdapter(mCartAdapter);
//全选和全不选
mCheckAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCartAdapter.checkAll(isChecked);
}
});
//设置总价回调器
mCartAdapter.setTotalPriceListener(this);
mGoodsList.setGroupIndicator(null);
mGoodsList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
@Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
return true;
}
});
cartPresenter.requestData();
}
@Override
public void success(List<Shop> data) {
mCartAdapter.addAll(data);
int size = data.size();
//遍历所有group,将所有项设置成默认展开
for (int i = 0; i <size ; i++) {
mGoodsList.expandGroup(i);
}
mCartAdapter.notifyDataSetChanged();
}
@Override
public void fail(Result result) {
Toast.makeText(this, result.getCode() + " " + result.getMsg(), Toast.LENGTH_LONG).show();
}
@Override
public void totalPrice(double totalPrice) {
//更改总价
mSumPrice.setText(String.valueOf(totalPrice));
}
}
Model层
public class CartModel {
public static Result goodsList() {
String resultString = HttpUtils.get("http://www.zhaoapi.cn/product/getCarts?uid=71");
try {
Gson gson = new Gson();
Type type = new TypeToken<Result<List<Shop>>>() {
}.getType();
Result result = gson.fromJson(resultString, type);
return result;
} catch (Exception e) {
}
Result result = new Result();
result.setCode(-1);
result.setMsg("数据解析异常");
return result;
}
}
Presenter层
public class CartPresenter extends BasePresenter {
public CartPresenter(DataCall dataCall) {
super(dataCall);
}
@Override
protected Result getData(Object... args) {
Result result = CartModel.goodsList();//调用网络请求获取数据
return result;
}
}
抽象类BasePresenter
public abstract class BasePresenter {
DataCall dataCall;
public BasePresenter(DataCall dataCall){
this.dataCall = dataCall;
}
Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
Result result = (Result) msg.obj;
if (result.getCode()==0){
dataCall.success(result.getData());
}else{
dataCall.fail(result);
}
}
};
public void requestData(final Object...args){
new Thread(new Runnable() {
@Override
public void run() {
Message message = mHandler.obtainMessage();
message.obj = getData(args);
mHandler.sendMessage(message);
}
}).start();
}
protected abstract Result getData(Object...args);
public void unBindCall(){
this.dataCall = null;
}
}
View层
public interface DataCall<T> {
void success(T data);
void fail(Result result);
}
自定义控件
public class AddSubLayout extends LinearLayout implements View.OnClickListener {
private TextView mAddBtn,mSubBtn;
private TextView mNumText;
private AddSubListener addSubListener;
public AddSubLayout(Context context) {
super(context);
initView();
}
public AddSubLayout(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public AddSubLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public AddSubLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initView();
}
private void initView(){
//加载layout布局,第三个参数ViewGroup一定写成this
View view = View.inflate(getContext(),R.layout.activity_add_btn,this);
mAddBtn = view.findViewById(R.id.btn_add);
mSubBtn = view.findViewById(R.id.btn_sub);
mNumText = view.findViewById(R.id.text_number);
mAddBtn.setOnClickListener(this);
mSubBtn.setOnClickListener(this);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
int width = r-l;//getWidth();
int height = b-t;//getHeight();
}
@Override
public void onClick(View v) {
int number = Integer.parseInt(mNumText.getText().toString());
switch (v.getId()){
case R.id.btn_add:
number++;
mNumText.setText(number+"");
break;
case R.id.btn_sub:
if (number==0){
Toast.makeText(getContext(),"数量不能小于0",Toast.LENGTH_LONG).show();
return;
}
number--;
mNumText.setText(number+"");
break;
}
if (addSubListener!=null){
addSubListener.addSub(number);
}
}
public void setCount(int count) {
mNumText.setText(count+"");
}
public void setAddSubListener(AddSubListener addSubListener) {
this.addSubListener = addSubListener;
}
public interface AddSubListener{
void addSub(int count);
}
}
适配器
public class CartAdapter extends BaseExpandableListAdapter {
private List<Shop> mList = new ArrayList<>();
private TotalPriceListener totalPriceListener;
private Context context;
public CartAdapter(Context context) {
this.context = context;
}
public void setTotalPriceListener(TotalPriceListener totalPriceListener) {
this.totalPriceListener = totalPriceListener;
}
@Override
public int getGroupCount() {
return mList.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return mList.get(groupPosition).getList().size();
}
@Override
public Object getGroup(int groupPosition) {
return mList.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return mList.get(groupPosition).getList().get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
//主条目
public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
GroupHodler hodler = null;
if (convertView == null) {
convertView = View.inflate(context, R.layout.activity_shop2_item, null);
hodler = new GroupHodler();
hodler.checkBox = convertView.findViewById(R.id.checkBox);
convertView.setTag(hodler);
} else {
hodler = (GroupHodler) convertView.getTag();
}
final Shop shop = mList.get(groupPosition);
hodler.checkBox.setText(shop.getSellerName());
hodler.checkBox.setChecked(shop.isCheck());
hodler.checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CheckBox checkBox = (CheckBox) v;
shop.setCheck(checkBox.isChecked());
//获得商品信息
List<Goods> goodsList = mList.get(groupPosition).getList();
//商品信息循环赋值
for (int i = 0; i < goodsList.size(); i++) {
//商铺选中则商品必须选中
goodsList.get(i).setSelected(checkBox.isChecked() ? 1 : 0);
}
//刷新列表
notifyDataSetChanged();
//重新计算总价
calculate();
}
});
return convertView;
}
@Override //子条目
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
MyHolder holder = null;
if (convertView == null) {
convertView = View.inflate(context, R.layout.activity_shop_item, null);
holder = new MyHolder();
holder.text = convertView.findViewById(R.id.text);
holder.price = convertView.findViewById(R.id.text_price);
holder.image = convertView.findViewById(R.id.image);
holder.addSub = convertView.findViewById(R.id.add_sub_layout);
holder.check = convertView.findViewById(R.id.cart_goods_check);
convertView.setTag(holder);
} else {
holder = (MyHolder) convertView.getTag();
}
final Goods goods = mList.get(groupPosition).getList().get(childPosition);
holder.text.setText(goods.getTitle());
holder.price.setText("单价:"+goods.getPrice());//单价
holder.check.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CheckBox checkBox = (CheckBox) v;
goods.setSelected(checkBox.isChecked()?1:0);
calculate();//计算价格
}
});
//判断是否选中
if (goods.getSelected() == 0) {
holder.check.setChecked(false);
}else {
holder.check.setChecked(true);
}
String imageurl = "https" + goods.getImages().split("https")[1];
imageurl = imageurl.substring(0, imageurl.lastIndexOf(".jpg") + ".jpg".length());
Glide.with(context).load(imageurl).into(holder.image);//加载图片
holder.addSub.setCount(goods.getNum());//设置商品数量
holder.addSub.setAddSubListener(new AddSubLayout.AddSubListener() {
@Override
public void addSub(int count) {
goods.setNum(count);
calculate();//计算价格
}
});
return convertView;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
public void addAll(List<Shop> data) {
if (data != null)
mList.addAll(data);
}
/**
* 全部选中或者取消
*/
public void checkAll(boolean isCheck) {
//循环的商家
for (int i = 0; i < mList.size(); i++) {
Shop shop = mList.get(i);
//商家选中
shop.setCheck(isCheck);
for (int j = 0; j < shop.getList().size(); j++) {
Goods goods = shop.getList().get(j);
//商品选中
goods.setSelected(isCheck ? 1 : 0);
}
}
//刷新列表
notifyDataSetChanged();
//重新计算总价
calculate();
}
//计算总价
private void calculate() {
double totalPrice = 0;
for (int i = 0; i < mList.size(); i++) {
Shop shop = mList.get(i);
for (int j = 0; j < shop.getList().size(); j++) {
Goods goods = shop.getList().get(j);
//如果是选中状态
if (goods.getSelected() == 1) {
//总价+=数量*单价 每一个商品总价相加=最终的总价
totalPrice += goods.getNum() * goods.getPrice();
}
}
}
if (totalPriceListener != null) {
totalPriceListener.totalPrice(totalPrice);
}
}
//总价接口 回调总价
public interface TotalPriceListener {
void totalPrice(double totalPrice);
}
class MyHolder {
CheckBox check;
TextView text;
TextView price;
ImageView image;
AddSubLayout addSub;
}
class GroupHodler {
CheckBox checkBox;
}
}
okHttp
public class HttpUtils {
public static String get(String urlString){
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(urlString).get().build();
try {
Response response = okHttpClient.newCall(request).execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public static String postForm(String url,String[] name,String[] value){
OkHttpClient okHttpClient = new OkHttpClient();
FormBody.Builder formBuild = new FormBody.Builder();
for (int i = 0; i < name.length; i++) {
formBuild.add(name[i],value[i]);
}
Request request = new Request.Builder().url(url).post(formBuild.build()).build();
try {
Response response = okHttpClient.newCall(request).execute();
String result = response.body().string();
Log.i("dt",result);
return result;
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public static String postFile(String url,String[] name,String[] value,String fileParamName,File file){
OkHttpClient okHttpClient = new OkHttpClient();
MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
if(file != null){
// MediaType.parse() 里面是上传的文件类型。
RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
String filename = file.getName();
// 参数分别为: 文件参数名 ,文件名称 , RequestBody
requestBody.addFormDataPart(fileParamName, "jpg", body);
}
if (name!=null) {
for (int i = 0; i < name.length; i++) {
requestBody.addFormDataPart(name[i], value[i]);
}
}
Request request = new Request.Builder().url(url).post(requestBody.build()).build();
try {
Response response = okHttpClient.newCall(request).execute();
if (response.code()==200) {
return response.body().string();
}
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public static String postJson(String url,String jsonString){
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),jsonString);
Request request = new Request.Builder().url(url).post(requestBody).build();
try {
Response response = okHttpClient.newCall(request).execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}
布局 activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".activity.MainActivity">
<ExpandableListView
android:id="@+id/list_cart"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
</ExpandableListView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp">
<CheckBox
android:id="@+id/check_all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:text="全选" />
<TextView
android:id="@+id/goods_sum_price"
android:layout_toRightOf="@+id/check_all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="价格:"
android:layout_marginLeft="20dp"
android:layout_centerVertical="true"/>
</RelativeLayout>
</LinearLayout>
activity_shop_item.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="horizontal">
<CheckBox
android:id="@+id/cart_goods_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"/>
<ImageView
android:id="@+id/image"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:minHeight="50dp"
android:layout_toRightOf="@+id/cart_goods_check"
android:src="@mipmap/ic_launcher"/>
<TextView
android:id="@+id/text"
android:layout_toRightOf="@+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="aa"
android:padding="10dp"/>
<TextView
android:id="@+id/text_price"
android:layout_toRightOf="@+id/image"
android:layout_below="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="价格"
android:padding="10dp"/>
<!--自定义控件-->
<zhao.com.shop.activity.AddSubLayout
android:id="@+id/add_sub_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginRight="20dp"
android:layout_marginBottom="20dp">
</zhao.com.shop.activity.AddSubLayout>
</RelativeLayout>
activity_shop2_item.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:focusable="false"
android:text="CheckBox" />
</LinearLayout>
activity_add_btn.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/btn_add"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="@drawable/sele_color_btn"
android:focusable="false"
android:textSize="20sp"
android:gravity="center"
android:text="+" />
<TextView
android:id="@+id/text_number"
android:layout_width="60dp"
android:layout_height="30dp"
android:gravity="center"
android:textSize="14sp"
android:text="1000" />
<TextView
android:id="@+id/btn_sub"
android:layout_width="30dp"
android:layout_height="30dp"
android:textSize="20sp"
android:focusable="false"
android:gravity="center"
android:background="@drawable/sele_color_btn"
android:text="-" />
</LinearLayout>