依赖
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.github.bumptech.glide:glide:4.8.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation('com.jcodecraeer:xrecyclerview:1.5.9') {
exclude group: 'com.android.support'
}
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
mainActivity的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="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorAccent"
android:gravity="center"
android:padding="10dp"
android:text="购物车"
android:textColor="#fff"
android:textSize="25sp" />
<ExpandableListView
android:id="@+id/list_cart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<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>
MainActivity
public class MainActivity extends AppCompatActivity implements CallBacks<List<Shop>>,CartAdapter2.TotalPriceListener{
private TextView mSumPrice;
private CheckBox mCheckAll;
private CartAdapter2 mCartAdapter;
private ExpandableListView mGoodsList;
private CartPresenter cartPresenter = new CartPresenter(this);
@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);
mCheckAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCartAdapter.checkAll(isChecked);
}
});
mGoodsList =findViewById(R.id.list_cart);
mCartAdapter = new CartAdapter2();
mGoodsList.setAdapter(mCartAdapter);
mCartAdapter.setTotalPriceListener(this);//设置总价回调器
mGoodsList.setGroupIndicator(null);
mGoodsList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
return true;
}
});
cartPresenter.requestData();
}
@Override
public void success(List<Shop> data) {
mCartAdapter.addAll(data);
//遍历所有group,将所有项设置成默认展开
int groupCount=data.size();
for (int i = 0; i <groupCount ; i++) {
mGoodsList.expandGroup(i);
}
mCartAdapter.notifyDataSetChanged();
}
@Override
public void fail(Result result) {
Toast.makeText(MainActivity.this, result.getCode() + " " + result.getMsg(), Toast.LENGTH_LONG).show();
}
@Override
public void totalPrice(double totalPrice) {
mSumPrice.setText(String.valueOf(totalPrice));
}
}
自定义view加减java按钮
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();
}
private void initView() {
//加载layout布局,第三个参数ViewGroup一定写成this
View view = View.inflate(getContext(),R.layout.add_btn_item,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);
}
}
自定义view的xml布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/btn_add"
android:layout_width="30dp"
android:layout_height="30dp"
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:text="-" />
</LinearLayout>
<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:text="-" />
二级列表的子view
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<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"/>
<com.example.lenovo.myapplication.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.example.lenovo.myapplication.AddSubLayout>
<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"/>
</RelativeLayout>
二级列表的父级的view
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<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"/>
<com.example.lenovo.myapplication.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.example.lenovo.myapplication.AddSubLayout>
<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"/>
</RelativeLayout>
两个二级列表的adapter
public class CartAdapter2 extends BaseExpandableListAdapter {
private List<Shop> mList = new ArrayList<>();
private TotalPriceListener totalPriceListener;
public CartAdapter2(){
}
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.layout_father,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).setSellerid(isChecked?1:0);
}
notifyDataSetChanged();
calculatePrice();
}
});
return convertView;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
MyHolder holder;
if (convertView==null){
convertView=View.inflate(parent.getContext(),R.layout.layout_child,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());
if (parent.getContext()!=null){
Glide.with(DTApplication.getInstance()).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;
}
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();
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}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;
}
class GroupHodler {
CheckBox checkBox;
}
public interface TotalPriceListener{
void totalPrice(double totalPrice);
}
}
全局类
public class DTApplication extends Application {
private static DTApplication instance;
private SharedPreferences mSharedPreferences;
@Override
public void onCreate() {
super.onCreate();
instance = this;
mSharedPreferences = getSharedPreferences("application",
Context.MODE_PRIVATE);
// JPushInterface.setDebugMode(true);
// JPushInterface.init(this); // 初始化 JPush
}
public static DTApplication getInstance() {
return instance;
}
public SharedPreferences getShare() {
return mSharedPreferences;
}
}
Callback正确失败类
public interface CallBacks<T> {
void success(T data);
void fail(Result result);
}
Result
int code;
String msg;
T data;
Shop类
List<Goods> list;
String sellerName;
String sellerid;
int textColor = 0xffffffff;
int background ;
boolean check;
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;
CartPrecenter
public class CartPresenter {
CallBacks callBacks;
public CartPresenter(CallBacks callBacks) {
this.callBacks=callBacks;
}
Handler handler=new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Result result = (Result) msg.obj;
if (result.getCode()==0){
callBacks.success(result.getData());
}else{
callBacks.fail(result);
}
}
};
public void requestData(){
new Thread(new Runnable() {
@Override
public void run() {
Result result=CartModel.add();
Message message = handler.obtainMessage();
message.obj =result;
handler.sendMessage(message);
}
}).start();
}
}
model
public class CartModel {
public static Result add() {
String s=ListUtils.add("http://www.zhaoapi.cn/product/getCarts?uid=71");
Gson gson=new Gson();
Type type=new TypeToken<Result<List<Shop>>>(){}.getType();
Result result=gson.fromJson(s,type);
return result;
}
}
Utis获取网络工具类
public class ListUtils {
public static String add(String urls) {
OkHttpClient okHttpClient=new OkHttpClient();
Request request=new Request.Builder().url(urls).build();
Call call=okHttpClient.newCall(request);
try {
Response execute = call.execute();
return execute.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}