效果图
导入依赖
apply plugin: 'com.android.application' android { compileSdkVersion 26 defaultConfig { applicationId "com.example.samsung.myapplication" minSdkVersion 15 targetSdkVersion 26 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:26.1.0' implementation 'com.android.support.constraint:constraint-layout:1.0.2' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.1' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' compile 'com.squareup.retrofit2:converter-gson:2.3.0' compile 'com.squareup.okhttp3:okhttp:3.4.1' compile 'com.jakewharton:butterknife:8.8.1' compile 'com.facebook.fresco:fresco:0.12.0' compile 'org.greenrobot:eventbus:3.1.1' compile 'com.android.support:recyclerview-v7:26.0.0-alpha1' compile 'io.reactivex.rxjava2:rxjava:2.1.7' compile 'io.reactivex.rxjava2:rxandroid:2.0.1' compile 'com.squareup.retrofit2:retrofit:2.3.0' compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0' annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1' }添加权限
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.samsung.myapplication"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <application android:name=".MyApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".view.Main2Activity"></activity> </application> </manifest>layout 下 activity-main 布局
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:fresco="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="com.example.samsung.myapplication.MainActivity"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <com.facebook.drawee.view.SimpleDraweeView android:id="@+id/goods_img" android:scaleType="centerCrop" android:layout_width="match_parent" android:layout_height="200dp" fresco:placeholderImage="@mipmap/ic_launcher" /> <LinearLayout android:orientation="vertical" android:padding="20dp" android:layout_width="wrap_content" android:layout_height="match_parent"> <TextView android:id="@+id/goods_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="按时打算打算大撒打算打算打算的" /> <TextView android:id="@+id/goods_prices" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="$199999" /> <TextView android:id="@+id/goods_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="我是商家" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_alignParentBottom="true" android:layout_width="match_parent" android:layout_height="50dp"> <Button android:id="@+id/add_btn" android:text="加入购物车" android:background="#f00" android:textColor="#fff" android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="match_parent" /> <Button android:text="立即购买" android:background="#efaf0d" android:layout_weight="1" android:textColor="#fff" android:layout_width="wrap_content" android:layout_height="match_parent" /> </LinearLayout> </RelativeLayout>layout 下 activity_main2 布局
<?xml version="1.0" encoding="utf-8"?> <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="com.example.samsung.myapplication.view.Main2Activity"> <TextView android:layout_width="match_parent" android:layout_height="50dp" android:gravity="center" android:text="购物车" android:textColor="#ff3660" android:textSize="25sp" /> <ExpandableListView android:id="@+id/elv" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="50dp" android:layout_alignParentBottom="true" android:background="@android:color/white" android:gravity="center_vertical"> <CheckBox android:id="@+id/checkbox2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="10dp" android:focusable="false" /> <TextView android:layout_width="wrap_content" android:layout_height="50dp" android:layout_centerVertical="true" android:layout_marginLeft="10dp" android:layout_toRightOf="@+id/checkbox2" android:gravity="center_vertical" android:text="全选" android:textSize="20sp" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:text="合计 :" /> <TextView android:id="@+id/tv_price" android:layout_width="wrap_content" android:layout_height="50dp" android:layout_marginLeft="10dp" android:paddingRight="10dp" android:text="0" android:textColor="@android:color/holo_red_light" /> <TextView android:id="@+id/tv_num" android:layout_width="wrap_content" android:layout_height="50dp" android:background="@android:color/holo_red_dark" android:gravity="center" android:padding="10dp" android:text="结算(0)" android:textColor="@android:color/white" /> </LinearLayout> </RelativeLayout> </LinearLayout>layout 下 child_layou 布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:fresco="http://schemas.android.com/apk/res-auto" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="horizontal"> <CheckBox android:id="@+id/cb_child" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:focusable="false" /> <!--<ImageView--> <!--android:id="@+id/img_icon"--> <!--android:layout_width="80dp"--> <!--android:layout_height="80dp"--> <!--android:src="@mipmap/ic_launcher" />--> <com.facebook.drawee.view.SimpleDraweeView android:id="@+id/my_image_view" android:layout_width="80dp" android:layout_height="80dp" fresco:placeholderImage="@mipmap/ic_launcher" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:orientation="vertical"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/tv_tel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:singleLine="true" android:text="iphone6" /> <TextView android:id="@+id/tv_pri" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="¥3000.00" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:gravity="center_vertical"> <com.example.samsung.myapplication.adapter.AddDeleteView android:id="@+id/adv_main" android:layout_width="wrap_content" android:layout_height="wrap_content" app:left_text="-" app:middle_text="3" app:right_text="+"></com.example.samsung.myapplication.adapter.AddDeleteView> </LinearLayout> </LinearLayout> <TextView android:id="@+id/tv_del" android:layout_width="40dp" android:layout_height="40dp" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginRight="10dp" android:layout_marginTop="25dp" android:gravity="center" android:text="删除" /> </RelativeLayout> </LinearLayout> </LinearLayout>layout 下 group_layout 布局
<?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"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/white" > <CheckBox android:id="@+id/cb_parent" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="10dp" android:layout_marginRight="4dp" android:checkMark="?android:attr/listChoiceIndicatorMultiple" android:gravity="center" android:minHeight="38dp" android:minWidth="32dp" android:textAppearance="?android:attr/textAppearanceLarge" android:visibility="visible" /> <TextView android:id="@+id/tv_number" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginBottom="10dp" android:layout_marginTop="10dp" android:layout_toRightOf="@id/cb_parent" android:background="@android:color/white" android:drawablePadding="10dp" android:textColor="#666666" android:textSize="18sp" /> </RelativeLayout> </LinearLayout>layout 下 layout_add_delete 布局
<?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"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <Button android:id="@+id/but_delete" android:layout_width="22dp" android:layout_height="22dp" android:background="@mipmap/remove" /> <TextView android:id="@+id/et_number" android:layout_width="40dp" android:inputType="number" android:layout_height="wrap_content" android:gravity="center" /> <Button android:id="@+id/but_add" android:layout_width="20dp" android:layout_height="20dp" android:background="@mipmap/add" /> </LinearLayout> </LinearLayout>主包下 MainActivity 类
package com.example.samsung.myapplication; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.example.samsung.myapplication.bean.GoodsBean; import com.example.samsung.myapplication.bean.MessageBean; import com.example.samsung.myapplication.presenter.DelPresenter; import com.example.samsung.myapplication.presenter.NewsPresenter; import com.example.samsung.myapplication.view.Iview; import com.example.samsung.myapplication.view.Main2Activity; import com.facebook.drawee.view.SimpleDraweeView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class MainActivity extends AppCompatActivity implements Iview { @BindView(R.id.goods_img) SimpleDraweeView mGoodsImg; @BindView(R.id.goods_title) TextView mGoodsTitle; @BindView(R.id.goods_prices) TextView mGoodsPrices; @BindView(R.id.goods_name) TextView mGoodsName; @BindView(R.id.add_btn) Button mAddBtn; // http://120.27.23.105/product/getProductDetail?pid=1&source=android @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); NewsPresenter presenter = new NewsPresenter(); presenter.attachView(this); presenter.getData("","1", "1"); } //回调方法 @Override public void onSuccess(Object o) { GoodsBean bean = (GoodsBean) o; if (bean != null) { GoodsBean.DataBean data = bean.getData(); String images = data.getImages(); String[] split = images.split("\\|"); //给控件赋值 mGoodsImg.setImageURI(split[0]); mGoodsName.setText(bean.getSeller().getDescription()); mGoodsPrices.setText("¥"+data.getBargainPrice()); mGoodsTitle.setText(data.getTitle()); } } @Override public void onFailed(Exception e) { } @Override public void delSuccess(MessageBean listMessageBean) { if(listMessageBean!=null){ String msg = listMessageBean.getMsg(); // Log.e("zxz",msg); Toast.makeText(this,msg,Toast.LENGTH_SHORT).show(); if(msg.equals("加购成功")){ Intent intent = new Intent(MainActivity.this, Main2Activity.class); startActivity(intent); } } } @OnClick(R.id.add_btn) public void onClick(View v) { switch (v.getId()) { default: break; case R.id.add_btn: DelPresenter delPresenter = new DelPresenter(); delPresenter.attachView(this); delPresenter.getData("addCart","3027","1"); break; } } }主包下 MyApplication 类
package com.example.samsung.myapplication; import android.app.Application; import com.facebook.drawee.backends.pipeline.Fresco; public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); Fresco.initialize(this); } }主包下 LoggingInterceptor 类
package com.example.samsung.myapplication; import java.io.IOException; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; public class LoggingInterceptor 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); } }主包下 ApiService 接口
package com.example.samsung.myapplication; import com.example.samsung.myapplication.bean.DatasBean; import com.example.samsung.myapplication.bean.GoodsBean; import com.example.samsung.myapplication.bean.MessageBean; import java.util.List; import io.reactivex.Flowable; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; public interface ApiService { @GET("product/getCarts") Flowable<MessageBean<List<DatasBean>>> getDatas(@Query("uid") String uid); // @GET("product/deleteCart") // Flowable<MessageBean> deleteData(@Query("uid") String uid, @Query("pid") String pid); @GET("product/{user}") Flowable<MessageBean> addData(@Path("user") String user, @Query("uid") String uid, @Query("pid") String pid); // http://120.27.23.105/product/getProductDetail?pid=1&source=android @GET("product/getProductDetail") Flowable<GoodsBean> selectData(@Query("pid") String pid); }adapter 包下 AddDeleteView 类
package com.example.samsung.myapplication.adapter; import android.content.Context; import android.content.res.TypedArray; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.example.samsung.myapplication.R; public class AddDeleteView extends LinearLayout { private OnAddDelClickListener listener; private TextView et_number; public void setOnAddDelClickListener(OnAddDelClickListener listener) { if (listener != null) { this.listener = listener; } } interface OnAddDelClickListener{ void onAddClick(View v); void onDelClick(View v); } public AddDeleteView(Context context) { this(context,null); } public AddDeleteView(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public AddDeleteView(Context context, @Nullable 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); Button but_add = findViewById(R.id.but_add); Button but_delete = findViewById(R.id.but_delete); et_number = findViewById(R.id.et_number); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AddDeleteViewStyle); String left_text = typedArray.getString(R.styleable.AddDeleteViewStyle_left_text); String middle_text = typedArray.getString(R.styleable.AddDeleteViewStyle_middle_text); String right_text = typedArray.getString(R.styleable.AddDeleteViewStyle_right_text); et_number.setText(middle_text); //释放资源 typedArray.recycle(); but_add.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { listener.onAddClick(view); } }); but_delete.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { listener.onDelClick(view); } }); } /** * 对外提供设置EditText值的方法 */ public void setNumber(int number){ if (number>0){ et_number.setText(number+""); } } /** * 得到控件原来的值 */ public int getNumber(){ int number = 0; try { String numberStr = et_number.getText().toString().trim(); number = Integer.valueOf(numberStr); } catch (Exception e) { number = 0; } return number; } }adapter 包下 MyAdapter 类
package com.example.samsung.myapplication.adapter; import android.content.Context; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.samsung.myapplication.R; import com.example.samsung.myapplication.bean.DatasBean; import com.example.samsung.myapplication.bean.MessageEvent; import com.example.samsung.myapplication.bean.PriceAndCountEvent; import com.example.samsung.myapplication.bean.SomeId; import com.facebook.drawee.view.SimpleDraweeView; import org.greenrobot.eventbus.EventBus; import java.util.List; public class MyAdapter extends BaseExpandableListAdapter { private Context context; private List<DatasBean> groupList; private List<List<DatasBean.ListBean>> childList; public MyAdapter(Context context, List<DatasBean> groupList, List<List<DatasBean.ListBean>> childList) { this.context =context; this.groupList = groupList; this.childList = childList; } @Override public int getGroupCount() { return groupList.size(); } @Override public int getChildrenCount(int i) { return childList.get(i).size(); } @Override public Object getGroup(int i) { return groupList.get(i); } @Override public Object getChild(int i, int i1) { return childList.get(i).get(i1); } @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) { final GroupViewHolder holder; if (view == null) { holder = new GroupViewHolder(); view = view.inflate(context, R.layout.group_layout, null); holder.cbGroup = view.findViewById(R.id.cb_parent); holder.tv_number = view.findViewById(R.id.tv_number); view.setTag(holder); } else { holder = (GroupViewHolder) view.getTag(); } final DatasBean dataBean = groupList.get(i); holder.cbGroup.setChecked(dataBean.isChecked()); // holder.tv_number.setText(dataBean.getTitle()); holder.tv_number.setText(dataBean.getSellerName()); //一级checkbox holder.cbGroup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dataBean.setChecked(holder.cbGroup.isChecked()); changeChildCbState(i, holder.cbGroup.isChecked()); EventBus.getDefault().post(compute()); changeAllCbState(isAllGroupCbSelected()); notifyDataSetChanged(); } }); return view; } @Override public View getChildView(final int i, final int i1, boolean b, View view, ViewGroup viewGroup) { final ChildViewHolder holder; if (view == null) { holder = new ChildViewHolder(); view = view.inflate(context,R.layout.child_layout, null); holder.cbChild = view.findViewById(R.id.cb_child); holder.tv_tel = view.findViewById(R.id.tv_tel); holder.tv_num =view.findViewById(R.id.tv_num); holder.draweeView = (SimpleDraweeView) view.findViewById(R.id.my_image_view); // holder.iv_add = view.findViewById(R.id.iv_add); // holder.iv_del = view.findViewById(R.id.iv_del); holder.tv_price = view.findViewById(R.id.tv_pri); holder.tv_del = view.findViewById(R.id.tv_del); holder.adv = view.findViewById(R.id.adv_main); view.setTag(holder); } else { holder = (ChildViewHolder) view.getTag(); } final DatasBean.ListBean datasBean = childList.get(i).get(i1); holder.cbChild.setChecked(datasBean.isChecked()); holder.tv_tel.setText(datasBean.getTitle()); // holder.tv_num.setText(datasBean.getNum()+""); holder.tv_price.setText("¥"+datasBean.getPrice() ); holder.adv.setNumber(datasBean.getNum()); String images = datasBean.getImages().trim(); String[] split = images.split("[|]"); holder.draweeView.setImageURI(split[0]); //二级checkbox holder.cbChild.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //设置该条目对象里的checked属性值 datasBean.setChecked(holder.cbChild.isChecked()); PriceAndCountEvent priceAndCountEvent = compute(); EventBus.getDefault().post(priceAndCountEvent); if (holder.cbChild.isChecked()) { //当前checkbox是选中状态 if (isAllChildCbSelected(i)) { changGroupCbState(i, true); changeAllCbState(isAllGroupCbSelected()); } } else { changGroupCbState(i, false); changeAllCbState(isAllGroupCbSelected()); } notifyDataSetChanged(); } }); holder.adv.setOnAddDelClickListener(new AddDeleteView.OnAddDelClickListener() { @Override public void onAddClick(View v) { Log.i("zxz", "onAddClick: 执行"); int origin = holder.adv.getNumber(); origin++; // holder.adv.setNumber(origin); int num = datasBean.getNum(); num++; holder.adv.setNumber(num); datasBean.setNum(num); if (holder.cbChild.isChecked()) { EventBus.getDefault().post(compute()); } } @Override public void onDelClick(View v) { int origin = holder.adv.getNumber(); // int num = datasBean.getNum(); origin--; if (origin == 0) { Toast.makeText(context,"最小数量为1",Toast.LENGTH_SHORT).show(); return ; } holder.adv.setNumber(origin); datasBean.setNum(origin); if (holder.cbChild.isChecked()) { EventBus.getDefault().post(compute()); } } }); //删除 holder.tv_del.setOnClickListener(new View.OnClickListener() { private AlertDialog dialog; @Override public void onClick(View v) { final List<DatasBean.ListBean> datasBeen = childList.get(i); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("提示"); builder.setMessage("确认是否删除?"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int ii) { DatasBean.ListBean remove = datasBeen.remove(i1); if (datasBeen.size() == 0) { childList.remove(i); groupList.remove(i); int pid = datasBean.getPid(); SomeId someId = new SomeId(); someId.setPid(pid+""); EventBus.getDefault().post(someId); } EventBus.getDefault().post(compute()); notifyDataSetChanged(); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialog.dismiss(); } }); dialog = builder.create(); dialog.show(); } }); return view; } @Override public boolean isChildSelectable(int i, int i1) { return false; } class GroupViewHolder { CheckBox cbGroup; TextView tv_number; } class ChildViewHolder { CheckBox cbChild; TextView tv_tel; TextView tv_content; TextView tv_time; // ImageView imgIcon; SimpleDraweeView draweeView; TextView tv_price; TextView tv_del; ImageView iv_del; ImageView iv_add; TextView tv_num; AddDeleteView adv; } /** * 改变全选的状态 * * @param flag */ private void changeAllCbState(boolean flag) { MessageEvent messageEvent = new MessageEvent(); messageEvent.setChecked(flag); EventBus.getDefault().post(messageEvent); } /** * 改变一级列表checkbox状态 * * @param groupPosition */ private void changGroupCbState(int groupPosition, boolean flag) { // GoosBean.DataBean dataBean = groupList.get(groupPosition); DatasBean dataBean = groupList.get(groupPosition); dataBean.setChecked(flag); } /** * 改变二级列表checkbox状态 * * @param groupPosition * @param flag */ private void changeChildCbState(int groupPosition, boolean flag) { List<DatasBean.ListBean> datasBeen = childList.get(groupPosition); for (int i = 0; i < datasBeen.size(); i++) { DatasBean.ListBean datasBean = datasBeen.get(i); datasBean.setChecked(flag); } } /** * 判断一级列表是否全部选中 * * @return */ private boolean isAllGroupCbSelected() { for (int i = 0; i < groupList.size(); i++) { DatasBean dataBean = groupList.get(i); if (!dataBean.isChecked()) { return false; } } return true; } /** * 判断二级列表是否全部选中 * * @param groupPosition * @return */ private boolean isAllChildCbSelected(int groupPosition) { List<DatasBean.ListBean> datasBeen = childList.get(groupPosition); for (int i = 0; i < datasBeen.size(); i++) { DatasBean.ListBean datasBean = datasBeen.get(i); if (!datasBean.isChecked()) { return false; } } return true; } /** * 计算列表中,选中的钱和数量 */ private PriceAndCountEvent compute() { int count = 0; int price = 0; for (int i = 0; i < childList.size(); i++) { List<DatasBean.ListBean> datasBeen = childList.get(i); for (int j = 0; j < datasBeen.size(); j++) { DatasBean.ListBean datasBean = datasBeen.get(j); if (datasBean.isChecked()) { price += datasBean.getNum() * datasBean.getPrice(); count += datasBean.getNum(); } } } PriceAndCountEvent priceAndCountEvent = new PriceAndCountEvent(); priceAndCountEvent.setCount(count); priceAndCountEvent.setPrice(price); return priceAndCountEvent; } /** * 设置全选、反选 * * @param flag */ public void changeAllListCbState(boolean flag) { for (int i = 0; i < groupList.size(); i++) { changGroupCbState(i, flag); changeChildCbState(i, flag); } EventBus.getDefault().post(compute()); notifyDataSetChanged(); } public void isClick (boolean click){ } }bean 包下 DataBean 类
package com.example.samsung.myapplication.bean; import java.util.List; public class DatasBean { private String sellerName; private String sellerid; private List<ListBean> list; private boolean checked; public boolean isChecked() { return checked; } public void setChecked(boolean checked) { this.checked = checked; } 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; } public List<ListBean> getList() { return list; } public void setList(List<ListBean> list) { this.list = list; } public static class ListBean { private boolean checked; 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; public boolean isChecked() { return checked; } public void setChecked(boolean checked) { this.checked = checked; } 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; } } }bean 包下 GoodsBean 类
package com.example.samsung.myapplication.bean; public class GoodsBean { /** * msg : * seller : {"description":"我是商家17","icon":"http://120.27.23.105/images/icon.png","name":"商家17","productNums":999,"score":5,"sellerid":17} * code : 0 * data : {"bargainPrice":111.99,"createtime":"2017-10-14T21:39:05","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","itemtype":1,"pid":1,"price":118,"pscid":1,"salenum":0,"sellerid":17,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"} */ private String msg; private SellerBean seller; private String code; private DataBean data; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public SellerBean getSeller() { return seller; } public void setSeller(SellerBean seller) { this.seller = seller; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public DataBean getData() { return data; } public void setData(DataBean data) { this.data = data; } public static class SellerBean { /** * description : 我是商家17 * icon : http://120.27.23.105/images/icon.png * name : 商家17 * productNums : 999 * score : 5 * sellerid : 17 */ private String description; private String icon; private String name; private int productNums; private int score; private int sellerid; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getProductNums() { return productNums; } public void setProductNums(int productNums) { this.productNums = productNums; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public int getSellerid() { return sellerid; } public void setSellerid(int sellerid) { this.sellerid = sellerid; } } public static class DataBean { /** * bargainPrice : 111.99 * createtime : 2017-10-14T21:39:05 * detailUrl : https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends * images : https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg * itemtype : 1 * pid : 1 * price : 118 * pscid : 1 * salenum : 0 * sellerid : 17 * subhead : 每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下 * title : 北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g */ private double bargainPrice; private String createtime; private String detailUrl; private String images; private int itemtype; private int pid; private float price; private int pscid; private int salenum; private int sellerid; private String subhead; private String title; 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 getItemtype() { return itemtype; } public void setItemtype(int itemtype) { this.itemtype = itemtype; } public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public int getPscid() { return pscid; } public void setPscid(int pscid) { this.pscid = pscid; } public int getSalenum() { return salenum; } public void setSalenum(int salenum) { this.salenum = salenum; } 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; } } }bean 包下 MessageBean 类
package com.example.samsung.myapplication.bean; public class MessageBean<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; } }
bean 包下 MessageEvent 类
public class MessageEvent { private boolean checked; public boolean isChecked() { return checked; } public void setChecked(boolean checked) { this.checked = checked; } }bean 包下 PriceAndCountEvent 类
public class PriceAndCountEvent { private int price; private int count; public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getCount() { return count; } public void setCount(int count) { this.count = count; }bean 包下 SomeId 类
public class SomeId { private String pid; public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } }model 包下 DelModel 类
public class DelModel implements IModel{ private DelPresenter presenter; public DelModel(DelPresenter presenter){ this.presenter = presenter; } @Override public void getData(String user,String uid,String pid) { Flowable<MessageBean> delFlowable = RetrofitUtils.getInstance().getApiService().addData(user,uid,pid); presenter.delData(delFlowable); }model 包下 IModel 接口
public interface IModel { void getData(String user,String uid,String pid); }model 包下 NewsModel 类
public class NewsModel implements IModel{ private NewsPresenter presenter; public NewsModel(NewsPresenter presenter){ this.presenter = (NewsPresenter) presenter; } @Override public void getData(String user,String uid,String pid) { Flowable<MessageBean<List<DatasBean>>> flowable = RetrofitUtils.getInstance().getApiService().getDatas(uid); presenter.getNews(flowable); if(uid=="1"){ Flowable<GoodsBean> flowable2 = RetrofitUtils.getInstance().getApiService().selectData(pid); presenter.getGoods(flowable2); } } }presenter 包下 BasePresenter 接口
public interface BasePresenter { void getData(String user,String uid,String pid); }presenter 包下 DelPresenter 类
public class DelPresenter implements BasePresenter { private Iview iv; private DisposableSubscriber subscriber; public void attachView(Iview iv) { this.iv = iv; } public void detachView() { if (iv != null) { iv = null; } if (!subscriber.isDisposed()){ subscriber.dispose(); } } @Override public void getData(String user,String uid,String pid) { DelModel model = new DelModel(this); model.getData(user,uid,pid); } public void delData(Flowable<MessageBean> delFlowable) { subscriber = delFlowable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeWith(new DisposableSubscriber<MessageBean>() { @Override public void onNext(MessageBean listMessageBean) { if (listMessageBean != null) { iv.delSuccess(listMessageBean); } } @Override public void onError(Throwable t) { iv.onFailed((Exception) t); } @Override public void onComplete() { } }); } }presenter 包下 NewsPresenter 类
public class NewsPresenter implements BasePresenter { private Iview iv; private DisposableSubscriber subscriber; public void attachView(Iview iv) { this.iv = iv; } public void detachView() { if (iv != null) { iv = null; } if (!subscriber.isDisposed()){ subscriber.dispose(); } } @Override public void getData(String user,String uid,String pid) { NewsModel model = new NewsModel(this); model.getData(user,uid,pid); } public void getNews(Flowable<MessageBean<List<DatasBean>>> flowable) { subscriber = flowable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeWith(new DisposableSubscriber<MessageBean<List<DatasBean>>>() { @Override public void onNext(MessageBean<List<DatasBean>> listMessageBean) { if (listMessageBean != null) { List<DatasBean> list = listMessageBean.getData(); if (list != null) { iv.onSuccess(list); } } } @Override public void onError(Throwable t) { iv.onFailed((Exception) t); } @Override public void onComplete() { } }); } public void getGoods(Flowable<GoodsBean> flowable) { subscriber = flowable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeWith(new DisposableSubscriber<GoodsBean>() { @Override public void onNext(GoodsBean listMessageBean) { if (listMessageBean != null) { iv.onSuccess(listMessageBean); } } @Override public void onError(Throwable t) { iv.onFailed((Exception) t); } @Override public void onComplete() { } }); } }utils 包下 RetrofitUtils 类
public class RetrofitUtils { private static volatile RetrofitUtils instance; private ApiService apiService; private OkHttpClient client = new OkHttpClient .Builder() .addInterceptor(new LoggingInterceptor()) .build(); private RetrofitUtils(){ Retrofit retrofit = new Retrofit.Builder() .client(client) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .baseUrl("http://120.27.23.105/")//填入自己的基本链接即可 .build(); apiService = retrofit.create(ApiService.class); } public static RetrofitUtils getInstance(){ if (null==instance){ synchronized (RetrofitUtils.class){ if (instance==null){ instance = new RetrofitUtils(); } } } return instance; } public ApiService getApiService(){ return apiService; } }view 包下 Iview 接口
public interface Iview { void onSuccess(Object o); void onFailed(Exception e); void delSuccess(MessageBean listMessageBean); }view 包下 Main2Activity 类
public class Main2Activity extends AppCompatActivity implements Iview { private String uid = "3027"; private NewsPresenter presenter; private CheckBox mCheckbox2; private ExpandableListView mElv; /** * 0 */ private TextView mTvPrice; /** * 结算(0) */ private TextView mTvNum; private MyAdapter adapter; private List<DatasBean> groupList = new ArrayList<>(); private List<List<DatasBean.ListBean>> childList = new ArrayList<>(); private String pid; private DelPresenter delPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); supportRequestWindowFeature(Window.FEATURE_NO_TITLE); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main2); //EventBus注册 EventBus.getDefault().register(this); initView(); presenter = new NewsPresenter(); presenter.attachView(this); delPresenter = new DelPresenter(); delPresenter.attachView(this); adapter = new MyAdapter(this, groupList, childList); mElv.setAdapter(adapter); //监听,调用适配器中方法改变复选框状态 mCheckbox2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { adapter.changeAllListCbState(mCheckbox2.isChecked()); } }); } private void initView() { mElv = (ExpandableListView) findViewById(R.id.elv); mCheckbox2 = (CheckBox) findViewById(R.id.checkbox2); mTvPrice = (TextView) findViewById(R.id.tv_price); mTvNum = (TextView) findViewById(R.id.tv_num); } //实现接口中的方法 @Override public void onSuccess(Object o) { if(o!=null){ List<DatasBean> list = (List<DatasBean> )o; if(list!=null){ groupList.addAll(list); for (int i = 0; i < list.size(); i++) { List<DatasBean.ListBean> datas = list.get(i).getList(); childList.add(datas); } adapter.notifyDataSetChanged(); mCheckbox2.setChecked(true); adapter.changeAllListCbState(true); mElv.setGroupIndicator(null); for (int i=0;i<groupList.size();i++){ mElv.expandGroup(i); } } } } @Override public void onFailed(Exception e) { } //重写删除接口中的方法 @Override public void delSuccess(MessageBean listMessageBean) { Toast.makeText(this,listMessageBean.getMsg(), Toast.LENGTH_SHORT).show(); } @Override protected void onResume() { super.onResume(); presenter.getData("",uid,pid); } @Subscribe public void onMessageEvent(MessageEvent event) { mCheckbox2.setChecked(event.isChecked()); } @Subscribe public void onMessageEvent(PriceAndCountEvent event) { mTvNum.setText("结算(" + event.getCount() + ")"); mTvPrice.setText("¥"+event.getPrice() ); } @Subscribe public void onMessageEvent(SomeId event) { pid = event.getPid(); delPresenter.getData("deleteCart",uid,pid); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); if (presenter != null) { presenter.detachView(); } } }