//总布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".view.MainActivity">
<ExpandableListView
android:id="@+id/list_car"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
</ExpandableListView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="@+id/checkAll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="全选"/>
<TextView
android:layout_marginLeft="20dp"
android:id="@+id/priceAll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="总价:"/>
</LinearLayout>
</LinearLayout>
//MainActivity
public class MainActivity extends AppCompatActivity implements DataCall<List<Shop>>,CarAdapter.TotalPriceListener{
private CheckBox checkAll;
private TextView priceAll;
private ExpandableListView list_car;
private CarAdapter mCartAdapter;
private CartPresenter cartPresenter = new CartPresenter(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkAll = findViewById(R.id.checkAll);
priceAll = findViewById(R.id.priceAll);
list_car = findViewById(R.id.list_car);
checkAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCartAdapter.checkAll(isChecked);
}
});
mCartAdapter = new CarAdapter();
list_car.setAdapter(mCartAdapter);
mCartAdapter.setTotalPriceListener(this);//设置总价回调器
list_car.setGroupIndicator(null);
list_car.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
@Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
return true;
}
});
cartPresenter.requestData();
}
@Override
public void totalPrice(double totalPrice) {
priceAll.setText(String.valueOf(totalPrice));
}
@Override
public void success(List<Shop> data) {
mCartAdapter.addAll(data);
//遍历所有group,将所有项设置成默认展开
int groupCount = data.size();
for (int i = 0; i < groupCount; i++) {
list_car.expandGroup(i);
}
mCartAdapter.notifyDataSetChanged();
}
@Override
public void fail(Result result) {
cartPresenter.unBindCall();
Toast.makeText(this, result.getCode() + " " + result.getMsg(), Toast.LENGTH_LONG).show();
}
}
//适配器
public class CarAdapter extends BaseExpandableListAdapter {
private List<Shop> mList = new ArrayList<>();
private TotalPriceListener totalPriceListener;
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 holder;
if (convertView == null) {
convertView = View.inflate(parent.getContext(), R.layout.cart2_group_item, null);
holder = new GroupHodler();
holder.checkBox = convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);
} else {
holder = (GroupHodler) convertView.getTag();
}
final Shop shop = mList.get(groupPosition);
holder.checkBox.setText(shop.getSellerName());
holder.checkBox.setChecked(shop.isCheck());//设置商铺选中状态
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
shop.setCheck(isChecked);//数据更新
List<Goods> goodsList = mList.get(groupPosition).getList();//得到商品信息
for (int i = 0; i < goodsList.size(); i++) {//商品信息循环赋值
goodsList.get(i).setSelected(isChecked?1:0);//商铺选中则商品必须选中
}
notifyDataSetChanged();
//计算价格
calculatePrice();
}
});
return convertView;
}
@Override
public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
MyHolder holder;
if (convertView == null) {
convertView = View.inflate(parent.getContext(), R.layout.cart_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.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
goods.setSelected(isChecked?1:0);
calculatePrice();//计算价格
}
});
if (goods.getSelected()==0){
holder.check.setChecked(false);
}else{
holder.check.setChecked(true);
}
String imageurl = "https" + goods.getImages().split("https")[1];
Log.i("dt", "imageUrl: " + imageurl);
imageurl = imageurl.substring(0, imageurl.lastIndexOf(".jpg") + ".jpg".length());
Glide.with(parent.getContext()).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);
calculatePrice();//计算价格
}
});
return convertView;
}
/**
* @author dingtao
* @date 2018/12/18 7:33 PM
* 全部选中或者取消
*/
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();
calculatePrice();
}
/**
* @author dingtao
* @date 2018/12/18 7:01 PM
* 计算总价格
*/
private void calculatePrice(){
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 = totalPrice + goods.getNum() * goods.getPrice();
}
}
}
if (totalPriceListener!=null)
totalPriceListener.totalPrice(totalPrice);
}
public void addAll(List<Shop> data) {
if (data != null)
mList.addAll(data);
}
class MyHolder {
CheckBox check;
TextView text;
TextView price;
ImageView image;
AddSubLayout addSub;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
class GroupHodler {
CheckBox checkBox;
}
public interface TotalPriceListener{
void totalPrice(double totalPrice);
}
}
//接口
public interface DataCall {
void success(T data);
void fail(Result result);
}
//Bean类
public class Goods {
private double bargainPrice;
private String createtime;
private String detailUrl;
private String images;
private int num;
private int pid;
private double price;
private int pscid;
private int selected;
private int sellerid;
private String subhead;
private String title;
private int count=1;
public void setCount(int count) {
this.count = count;
}
public int getCount() {
return count;
}
public double getBargainPrice() {
return bargainPrice;
}
public void setBargainPrice(double bargainPrice) {
this.bargainPrice = bargainPrice;
}
public String getCreatetime() {
return createtime;
}
public void setCreatetime(String createtime) {
this.createtime = createtime;
}
public String getDetailUrl() {
return detailUrl;
}
public void setDetailUrl(String detailUrl) {
this.detailUrl = detailUrl;
}
public String getImages() {
return images;
}
public void setImages(String images) {
this.images = images;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getPscid() {
return pscid;
}
public void setPscid(int pscid) {
this.pscid = pscid;
}
public int getSelected() {
return selected;
}
public void setSelected(int selected) {
this.selected = selected;
}
public int getSellerid() {
return sellerid;
}
public void setSellerid(int sellerid) {
this.sellerid = sellerid;
}
public String getSubhead() {
return subhead;
}
public void setSubhead(String subhead) {
this.subhead = subhead;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
//Result
public class Result<T> {
private String msg;
private String code;
private T data;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public static class DataBean {
}
}
//Shop
public class Shop {
List<Goods> list;
String sellerName;
String sellerid;
int textColor = 0xffffffff;
int background = R.color.grayblack;
boolean check;
public void setTextColor(int textColor) {
this.textColor = textColor;
}
public int getTextColor() {
return textColor;
}
public void setBackground(int background) {
this.background = background;
}
public int getBackground() {
return background;
}
public void setCheck(boolean check) {
this.check = check;
}
public boolean isCheck() {
return check;
}
public List<Goods> getList() {
return list;
}
public void setList(List<Goods> list) {
this.list = list;
}
public String getSellerName() {
return sellerName;
}
public void setSellerName(String sellerName) {
this.sellerName = sellerName;
}
public String getSellerid() {
return sellerid;
}
public void setSellerid(String sellerid) {
this.sellerid = sellerid;
}
}
// HttpUtils
public class HttpUtils {
public static String get(String urlString){
// 添加日志拦截器
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)//连接超时
.readTimeout(20, TimeUnit.SECONDS)//读取超时
.callTimeout(20, TimeUnit.SECONDS)//呼叫超时
.addInterceptor(loggingInterceptor)// 日志拦截器
.build();
Request request = new Request.Builder().url(urlString).get().build();
// 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 "";
}
//Modle
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);
// Result<List<Goods>> result = new Result<>();
// result.setCode(0);
// List<Goods> list = new ArrayList<>();
// for (int i = 0; i < 30; i++) {
// Goods goods = new Goods();
// goods.setImages("");
// goods.setTitle("手机"+i);
// list.add(goods);
// }
// result.setData(list);
return result;
} catch (Exception e) {
}
Result result = new Result();
result.setCode("-1");
result.setMsg("数据解析异常");
return result;
}
}
//presenter
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().equals("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;
}
}
//CartPresenter
public class CartPresenter extends BasePresenter {
public CartPresenter(DataCall dataCall) {
super(dataCall);
}
@Override
protected Result getData(Object... args) {
Result result = CartModel.goodsList();//调用网络请求获取数据
return result;
}
}
//自定义view
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.car_add_sub_layout,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);
}
}
//购物车加减布局
car_add_sub_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
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/car_btn_bg"
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/car_btn_bg"
android:text="-" />
</LinearLayout>
//全选布局
cart2_group_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>
//条目的布局
cart_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:background="@drawable/search_edit_bg"
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"/>
<com.bawie.liu.beifen.view.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">
</com.bawie.liu.beifen.view.AddSubLayout>
</RelativeLayout>
values
<resources>
<color name="colorPrimary">#008577</color>
<color name="colorPrimaryDark">#00574B</color>
<color name="colorAccent">#D81B60</color>
<color name="white">#FFFFFF</color> <!-- 白色 -->
<color name="black">#000000</color> <!-- 黑色 -->
<color name="thinblue">#4186c9</color> <!-- 淡蓝色 -->
<color name="transparent">#00000000</color> <!-- 透明 -->
<color name="thingray">#dae8f5</color> <!-- 淡灰色 -->
<color name="thinwhite">#c6daf0</color> <!-- 浅白色 -->
<color name="gray">#ececec</color> <!-- 灰色 -->
<color name="grayblack">#999999</color> <!-- 灰黑色 -->
<color name="commonblack">#585858</color> <!-- 一般使用的黑色 -->
<color name="line_color">#d8d8d8</color> <!-- 单调的黑色 -->
<color name="radiocolor">#858a8e</color> <!-- 按钮颜色 -->
<color name="custom_gray">#656565</color> <!-- 通用灰 -->
<color name="list_black">#d0d0d0</color> <!-- 分隔线黑 -->
<color name="fontblack">#4f4f4f</color> <!-- 字体颜色 -->
<color name="fontgray">#5c5c5c</color> <!-- 字体灰 -->
<color name="graybg">#efefef</color>
<color name="gray_bg">#fbfbfb</color> <!-- 事件详情页信息背景 -->
<color name="blackgray">#E5E5E5</color> <!-- 深灰 -->
<color name="pure_gray">#f2f2f2</color> <!-- 纯色灰 -->
<color name="set_font_color">#686868</color>
<color name="set_title_color">#9a9a9a</color>
<color name="set_account_color">#57a6d8</color>
<color name="center_item_color">#575757</color>
<color name="titlebar_color">#4bc1d2</color>
<color name="set_line">#e4e4e4</color>
<color name="blue">#145fa6</color> <!-- 蓝色 -->
<color name="login_bg">#4cb3e8</color>
<color name="hintcolor">#cdcdcd</color>
<color name="tb_color">#f8f8f8</color>
<color name="center_checked_no_color">#909090</color>
<color name="msg_font_color">#555555</color>
<color name="mark_red">#ff4040</color> <!-- 红色 -->
<color name="gray_text">#666666</color>
<color name="topic_text_color">#767676</color>
<color name="filter_bg_color">#00FBFF</color>
<color name="gray_thin">#adadad</color>
<color name="topic_name_color">#6db3be</color>
<color name="topic_reply_color">#a9a9a9</color>
<color name="even_city_tui_color">#777678</color>
<color name="even_near_color">#f2f1f1</color>
<color name="even_near_small_color">#dfdfdf</color>
<color name="even_footer_color">#989696</color>
<color name="banner_join_press_color">#d4ecf1</color>
<color name="tb_text_color">#4f423a</color>
<color name="register_btn_color">#7ed321</color>
<color name="topic_reply_time_color">#9b9b9b</color>
<!-- 播的字体颜色 -->
<color name="bo_small_text_color">#CCCCCC</color>
<color name="bo_text_hint_color">#A4A4A4</color>
<color name="body_text_1">#ff000000</color>
<color name="body_text_2">#99000000</color>
<color name="body_text_disabled">#66000000</color>
<color name="body_text_1_inverse">#ffffffff</color>
<color name="body_text_2_inverse">#99ffffff</color>
<color name="accent_1">#ff29549f</color>
<color name="hyperlink">#ffff549f</color>
<color name="background_1">#ffffffff</color>
<color name="whats_on_separator">#4d000000</color>
<color name="all_track_color">#ff222222</color>
<color name="block_column_1">#ff0fabff</color>
<color name="block_column_2">#ffdf1831</color>
<color name="block_column_3">#ff009939</color>
<color name="umeng_fb_color_btn_pressed">#1495F7</color>
<color name="umeng_fb_color_btn_normal">#333333</color>
<color name="actionbar_background_start">#3A5FCD</color>
<color name="actionbar_background_end">#27408B</color>
</resources>
car_btn_bg.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<corners
android:radius="5dp"></corners>
<stroke
android:color="@android:color/holo_red_dark"
android:width="2dp">
</stroke>
search_edit_bg.xml
</shape>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="20dp" />
<solid
android:color="#d8d8d8"></solid>
</shape>