在做购物车的时候,我觉得是先布好局,当然了,我是用二级列表做的
activity_main.xml中的总布局:
<!--头布局--> <LinearLayout android:id="@+id/top_bar" android:layout_width="match_parent" android:layout_height="48dp" android:background="#f7f7f7" android:orientation="vertical" > <RelativeLayout android:layout_width="match_parent" android:layout_height="48dp" android:background="@android:color/transparent" android:orientation="vertical" > <ImageView android:id="@+id/back" android:layout_width="48dp" android:layout_height="48dp" android:layout_alignParentLeft="true" android:layout_gravity="center_vertical" android:padding="12dp" android:src="@drawable/back" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:minHeight="48dp" android:text="购物车" android:textColor="#1a1a1a" android:textSize="16sp" /> <TextView android:id="@+id/edit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_marginRight="40dp" android:gravity="center" android:minHeight="48dp" android:text="编辑" android:textColor="#1a1a1a" android:textSize="14sp" android:visibility="visible" /> </RelativeLayout> </LinearLayout> <ExpandableListView android:id="@+id/exListView" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:childIndicator="@null" android:groupIndicator="@null" > </ExpandableListView> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:gravity="center_vertical" android:orientation="horizontal" > <CheckBox android:id="@+id/all_chekbox" android:layout_marginLeft="20dp" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="全选"/> <LinearLayout android:id="@+id/ll_info" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="4" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_marginRight="20dp" android:layout_weight="1" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="right" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:text="合计:" android:textSize="18sp" android:textStyle="bold" /> <TextView android:id="@+id/total_price" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="¥0.00" android:textColor="#f23232" android:textSize="16sp" android:textStyle="bold" /> </LinearLayout> <TextView android:id="@+id/total_number" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="共有商品:0件" android:gravity="right" android:textSize="16sp" android:textStyle="bold" /> </LinearLayout> <TextView android:id="@+id/tv_go_to_pay" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="3" android:background="#fd7a05" android:clickable="true" android:gravity="center" android:text="结算" android:textColor="#FAFAFA" /> </LinearLayout> </LinearLayout>
group的布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#cfc3c3" android:orientation="horizontal"> <CheckBox android:id="@+id/group_checkbox" android:layout_marginLeft="20dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:focusable="false"/> <TextView android:id="@+id/shop_name" android:layout_marginLeft="20dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16dp" /> </LinearLayout>child的布局(里面有删除的自定义View)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="230dp" android:orientation="horizontal"> <CheckBox android:id="@+id/child_checkbox" android:layout_marginTop="50dp" android:layout_marginLeft="20dp" android:layout_marginBottom="50dp" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <RelativeLayout android:layout_marginLeft="20dp" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/shop_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginLeft="17dp" android:layout_marginStart="17dp" android:text="TextView" android:layout_alignParentTop="true" /> <ImageView android:id="@+id/shop_img" android:layout_width="90dp" android:layout_height="90dp" android:layout_marginTop="30dp" app:srcCompat="@mipmap/ic_launcher" android:layout_below="@+id/shop_name" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <TextView android:id="@+id/shop_price" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/shop_img" android:layout_centerHorizontal="true" android:layout_marginTop="10dp" android:text="¥20" android:textColor="#f23232"/> <dongzhou.bwie.com.shopcartactivity.AddDeleteView android:id="@+id/adv" android:layout_width="160dp" android:layout_height="30dp" android:layout_below="@+id/shop_price" android:layout_marginTop="30dp" android:layout_marginLeft="140dp" app:left_text="-" app:right_text="+" app:middle_text="1" android:focusable="false" > </dongzhou.bwie.com.shopcartactivity.AddDeleteView> <Button android:id="@+id/shop_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:visibility="invisible" android:text="删除" /> </RelativeLayout> </LinearLayout>删除的布局:
?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="1"> <TextView android:id="@+id/txt_delete" android:layout_width="30dp" android:layout_height="30dp" android:text="-" android:gravity="center" android:background="#8b948b"/> <EditText android:id="@+id/et_number" android:layout_marginTop="2dp" android:layout_width="50dp" android:layout_height="30dp" android:background="@drawable/edit" android:layout_weight="0.00" android:gravity="center" android:text="1"/> <TextView android:id="@+id/txt_add" android:layout_width="30dp" android:layout_height="30dp" android:text="+" android:gravity="center" android:background="#8b948b"/> </LinearLayout>做完了布局,我们就开始做正事吧(MVP)M层
GsonUtilspublic class GsonUtils { private static Gson gson; public static Gson getInstance(){ if(gson==null){ gson=new Gson(); } return gson; } }HttpUtils
public class HttpUtils { private static final String TAG = "HttpUtils"; private static volatile HttpUtils instance; Handler handler=new Handler(); public HttpUtils() { } public static HttpUtils getInstance(){ if(null==instance){ synchronized (HttpUtils.class){ if(instance==null){ instance = new HttpUtils(); } } } return instance; } public void get(String url, Map<String,String> map,final CallBack callBack, final Class cla, final String tag){ if(TextUtils.isEmpty(url)){ return; } StringBuffer sb=new StringBuffer(); sb.append(url); if(!map.isEmpty()){ Log.i(TAG, "get: url="+"开始拼接+++++++++++++++++"); if(url.contains("?")){ if(url.indexOf("?")==url.length()-1){ }else { sb.append("&"); } }else { sb.append("?"); } for (Map.Entry<String,String> entry:map.entrySet()){ sb.append(entry.getKey()) .append("=") .append(entry.getValue()) .append("&"); } if(sb.indexOf("&")!=-1){ sb.deleteCharAt(sb.lastIndexOf("&")); } } Log.i(TAG, "get: url="+sb); OkHttpClient client=new OkHttpClient.Builder(). addInterceptor(new Logger()).build() ; final Request request=new Request.Builder() .get() .url(sb.toString()) .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { handler.post(new Runnable() { @Override public void run() { callBack.onFailed(tag,e); } }); } @Override public void onResponse(Call call, Response response) throws IOException { final String result = response.body().string(); Log.e(TAG, "onResponse: result--"+result); handler.post(new Runnable() { @Override public void run() { Object o; if (TextUtils.isEmpty(result)) { o = null; } else { o = GsonUtils.getInstance().fromJson(result, cla); } //Log.e(TAG, "onResponse: bean--"+); callBack.onSuccess(tag, o); } }); } }); } }Logger
public class Logger implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request original = chain.request(); HttpUrl url=original.url().newBuilder() .addQueryParameter("source","android") .build(); //添加请求头 Request request = original.newBuilder() .url(url) .build(); return chain.proceed(request); } }接口ImView
public interface ImView { void onSuccess(String tag, Object o); void onFailed(String tag, Exception e); }CallBack
public interface CallBack { void onSuccess(String tag, Object o); void onFailed(String tag, Exception e); }P层public class Presenter { private ImView inv; public void attachView(ImView inv){ this.inv=inv; } public void get(String url, Map<String,String>map,String tag,Class clv){ HttpUtils.getInstance().get(url, map, new CallBack() { @Override public void onSuccess(String tag, Object o) { if(o!=null){ inv.onSuccess(tag,o); } } @Override public void onFailed(String tag, Exception e) { inv.onFailed(tag,e); } },clv,tag); } public void deleteView(){ if(inv!=null){ inv=null; } } }当然了,不要忘记适配器删除的逻辑public class ExpandableAdapter extends BaseExpandableListAdapter{ // private static final String TAG = "ExpandableAdapter二级列表适配器"; private Context context; private List<GroupBean> groupBeen=new ArrayList<>(); private List<List<ChildBean>> childBeen=new ArrayList<>(); public ExpandableAdapter(Context context, List<GroupBean> groupBeen, List<List<ChildBean>> childBeen) { this.context = context; this.groupBeen = groupBeen; this.childBeen = childBeen; } @Override public int getGroupCount() { return groupBeen.size(); } @Override public int getChildrenCount(int i) { return childBeen.get(i).size(); } @Override public Object getGroup(int i) { return groupBeen.get(i).getSellerName(); } @Override public Object getChild(int i, int i1) { return childBeen.get(i).get(i1).getTitle(); } @Override public long getGroupId(int i) { return i; } @Override public long getChildId(int i, int i1) { return i1; } @Override public boolean hasStableIds() { return false; } //一级组 @Override public View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) { //加载视图 view=View.inflate(context, R.layout.ex_group_item ,null); final CheckBox groupCb= (CheckBox) view.findViewById(R.id.group_checkbox); TextView shopName= (TextView) view.findViewById(R.id.shop_name); shopName.setText(groupBeen.get(i).getSellerName()); groupCb.setChecked(groupBeen.get(i).isGropuCb()); //组复选按钮 groupCb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boolean gchecked = groupCb.isChecked(); groupBeen.get(i).setGropuCb(gchecked); Main2Activity main= (Main2Activity) context; for(GroupBean i: groupBeen){ boolean gropuCb = i.isGropuCb(); if(!gropuCb){ main.allCheckbox.setChecked(false); break; }else{ main.allCheckbox.setChecked(true); } } int size = childBeen.get(i).size(); if(gchecked){ for(int r=0;r<size;r++){ //Toast.makeText(context,"group按钮"+ gchecked+""+size, Toast.LENGTH_SHORT).show(); childBeen.get(i).get(r).setChildCb(true); } }else{ for(int r=0;r<size;r++){ //Toast.makeText(context,"group按钮"+ gchecked+""+size, Toast.LENGTH_SHORT).show(); childBeen.get(i).get(r).setChildCb(false); } } notifyDataSetChanged(); main.changesum(childBeen); } }); return view; } //二级组 @Override public View getChildView(final int i, final int i1, boolean b, View v, ViewGroup viewGroup) { //加载视图 v=View.inflate(context, R.layout.ex_child_item ,null); final CheckBox childCb = (CheckBox) v.findViewById(R.id.child_checkbox); TextView shopTitle= (TextView) v.findViewById(R.id.shop_title); TextView shopPrice= (TextView) v.findViewById(R.id.shop_price); ImageView shopImg= (ImageView) v.findViewById(R.id.shop_img); final AddDeleteView adv = (AddDeleteView) v.findViewById(R.id.adv); Button shop_delete= (Button) v.findViewById(R.id.shop_delete); childCb.setChecked(childBeen.get(i).get(i1).isChildCb()); Glide.with(context).load(childBeen.get(i).get(i1).getImages()).into(shopImg); shopTitle.setText(childBeen.get(i).get(i1).getTitle()); shopPrice.setText(childBeen.get(i).get(i1).getPrice()+""); adv.setNumber(childBeen.get(i).get(i1).getNum()); final Main2Activity main= (Main2Activity) context; //控制删除按钮的显隐 if(childBeen.get(i).get(i1).isBtn()){ shop_delete.setVisibility(View.VISIBLE); }else{ shop_delete.setVisibility(View.INVISIBLE); } //删除按钮监听 shop_delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int size = childBeen.get(i).size(); if(size==1){ childBeen.remove(i); groupBeen.remove(i); }else{ childBeen.get(i).remove(i1); } //点击删除后隐藏所有删除按钮 for (List<ChildBean> i1:childBeen){ for(int r=0;r<i1.size();r++) { i1.get(r).setBtn(false); } } notifyDataSetChanged(); main.changesum(childBeen); } }); //加减器逻辑 adv.setOnAddDelClickListener(new AddDeleteView.OnAddDelClickListener() { @Override public void onAddClick(View v) { int number = adv.getNumber(); number++; adv.setNumber(number); childBeen.get(i).get(i1).setNum(number); main.changesum(childBeen); } @Override public void onDelClick(View v) { int number = adv.getNumber(); number--; adv.setNumber(number); childBeen.get(i).get(i1).setNum(number); main.changesum(childBeen); } }); //二级组的复选框监听 childCb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boolean flag=false; boolean cchecked = childCb.isChecked(); childBeen.get(i).get(i1).setChildCb(cchecked); //Toast.makeText(context,"child按钮"+ cchecked+""+i1, Toast.LENGTH_SHORT).show(); Main2Activity main= (Main2Activity) context; for (List<ChildBean> i1:childBeen){ for(int r=0;r<i1.size();r++) { boolean childCb1 = i1.get(r).isChildCb(); if(!childCb1){ main.allCheckbox.setChecked(false); groupBeen.get(i).setGropuCb(false); flag=true; break; }else{ main.allCheckbox.setChecked(true); groupBeen.get(i).setGropuCb(true); } } if(flag){ break; } } int size = childBeen.get(i).size(); for(int x=0;x<size;x++) { boolean childCb1 = childBeen.get(i).get(x).isChildCb(); if(!childCb1){ groupBeen.get(i).setGropuCb(false); break; }else{ groupBeen.get(i).setGropuCb(true); } } notifyDataSetChanged(); main.changesum(childBeen); } }); return v; } @Override public boolean isChildSelectable(int i, int i1) { return false; } }public class AddDeleteView extends LinearLayout { private OnAddDelClickListener listener; private EditText etNumber; //对外提供一个点击的回调接口 public interface OnAddDelClickListener{ void onAddClick(View v); void onDelClick(View v); } public void setOnAddDelClickListener(OnAddDelClickListener listener){ if(listener!=null){ this.listener=listener; } } public AddDeleteView(Context context) { this(context,null); } public AddDeleteView(Context context, AttributeSet attrs) { this(context, attrs,0); } public AddDeleteView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(context, attrs, defStyleAttr); } private void initView(Context context, AttributeSet attrs, int defStyleAttr) { View.inflate(context, R.layout.layout_add_delete,this); //获取控件 TextView txtDelete= (TextView) findViewById(R.id.txt_delete); TextView txtAdd= (TextView) findViewById(R.id.txt_add); etNumber = (EditText) findViewById(R.id.et_number); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AddDeleteViewStyle); String leftText = typedArray.getString(R.styleable.AddDeleteViewStyle_left_text); String rightText = typedArray.getString(R.styleable.AddDeleteViewStyle_right_text); String middleText = typedArray.getString(R.styleable.AddDeleteViewStyle_middle_text); int color = typedArray.getColor(R.styleable.AddDeleteViewStyle_left_text_color, Color.BLACK); txtDelete.setText(leftText); txtAdd.setText(rightText); etNumber.setText(middleText); txtDelete.setTextColor(color); //回收 typedArray.recycle(); txtDelete.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { listener.onDelClick(view); } }); txtAdd.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { listener.onAddClick(view); } }); } //对外提供一个修改数字的方法 public void setNumber(int number){ if(number>0){ etNumber.setText(number+""); } } //对外提供一个获取当前数字的方法 public int getNumber(){ String string = etNumber.getText().toString(); int i = Integer.parseInt(string); return i; } }Main_activity主文件展示public class Main2Activity extends AppCompatActivity implements ImView { private ExpandableListView exListView; public CheckBox allCheckbox; private TextView totalPrice; private TextView totalnumber; List<GroupBean> groupBeen=new ArrayList<>(); List<List<ChildBean>> childBeen=new ArrayList<>(); private Presenter presenter; private ExpandableAdapter expandableAdapter; private TextView edit; private boolean flagedit=true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); getSupportActionBar().hide(); initView(); presenter = new Presenter(); presenter.attachView(this); Map<String,String> map = new HashMap<>(); presenter.get("http://120.27.23.105/product/getCarts?uid=100",map,"car", ShopCarBean.class); //获取二级列表适配器 expandableAdapter = new ExpandableAdapter(Main2Activity.this, groupBeen, childBeen); exListView.setAdapter(expandableAdapter); for(int i = 0; i < expandableAdapter.getGroupCount(); i++){ exListView.expandGroup(i); } exListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) { return true; } }); //全选监听 allCheckbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boolean checked = allCheckbox.isChecked(); //改变一级item复选框 for (GroupBean i:groupBeen){ i.setGropuCb(checked); } //改变二级item复选框 for (List<ChildBean> i1:childBeen){ for(int r=0;r<i1.size();r++) { i1.get(r).setChildCb(checked); } } expandableAdapter.notifyDataSetChanged(); changesum(childBeen); //Toast.makeText(Main2Activity.this,"全选按钮"+checked,Toast.LENGTH_SHORT).show(); } }); edit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { for (List<ChildBean> i1:childBeen){ for(int r=0;r<i1.size();r++) { i1.get(r).setBtn(flagedit); } } flagedit=!flagedit; expandableAdapter.notifyDataSetChanged(); } }); } //初始化控件 private void initView() { exListView = (ExpandableListView) findViewById(R.id.exListView); allCheckbox = (CheckBox)findViewById(R.id.all_chekbox); totalPrice = (TextView)findViewById(R.id.total_price); totalnumber = (TextView)findViewById(R.id.total_number); edit = (TextView) findViewById(R.id.edit); } @Override public void onSuccess(String tag, Object o) { if(o!=null&&tag.equals("car")){ ShopCarBean shopCarBean= (ShopCarBean) o; List<ShopCarBean.DataBean> data = shopCarBean.getData(); for (ShopCarBean.DataBean i:data){ GroupBean groupBean = new GroupBean(i.getSellerName(), false); this.groupBeen.add(groupBean); List<ShopCarBean.DataBean.ListBean> list = i.getList(); List<ChildBean> ls=new ArrayList<>(); for (ShopCarBean.DataBean.ListBean w:list){ String[] split = w.getImages().split("\\|"); ChildBean childBean = new ChildBean(w.getTitle(), split[0], w.getPrice(), 1, false,false); ls.add(childBean); } this.childBeen.add(ls); } for(int i = 0; i < expandableAdapter.getGroupCount(); i++){ exListView.expandGroup(i); } expandableAdapter.notifyDataSetChanged(); } } @Override public void onFailed(String tag, Exception e) { Toast.makeText(Main2Activity.this,e.getMessage()+"",Toast.LENGTH_SHORT).show(); } //计算和数量总价 public void changesum(List<List<ChildBean>> childBeen){ int count=0; double sum=0; for (List<ChildBean> i1:childBeen){ for(int r=0;r<i1.size();r++) { boolean childCb1 = i1.get(r).isChildCb(); if(childCb1){ double price = i1.get(r).getPrice(); int num = i1.get(r).getNum(); sum+=price*num; count++; } } } totalPrice.setText("¥"+sum); totalnumber.setText("共有商品:"+count+"件"); } }