依赖
//okhttp
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
//okhttp的log信息
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
//gson
implementation 'com.google.code.gson:gson:2.8.5'
//glide
implementation 'com.github.bumptech.glide:glide:4.7.1'
//xrecyclerview
implementation 'com.jcodecraeer:xrecyclerview:1.5.9'
}
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
def requested = details.requested
if (requested.group == 'com.android.support') {
if (!requested.name.startsWith("multidex")) {
details.useVersion '27.1.1'
}
}
}
}
权限
<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" />
先写流式布局
自定义View
public class CustomView extends ViewGroup {
private int mleftMargin=20;
private int mtopMargin=20;
public CustomView(Context context) {
this(context,null);
}
public CustomView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
measureChildren(widthMeasureSpec,heightMeasureSpec);
int leftMargin = mleftMargin;
int topMargin = mtopMargin;
int viewHeight = 0;
int viewWidth = 0;
//父控件传进来的宽度和高度以及对应的测量模式
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
switch (modeHeight){
case MeasureSpec.AT_MOST:
int measuredHeight = 0;
for (int j = 0; j < getChildCount(); j++) {
int measuredWidth = getChildAt(j).getMeasuredWidth();
measuredHeight = getChildAt(j).getMeasuredHeight();
if (leftMargin+measuredWidth+mleftMargin>getWidth()){
leftMargin=mleftMargin;
topMargin+=measuredHeight+mtopMargin;
}
leftMargin+=measuredWidth+mleftMargin;
}
topMargin+=measuredHeight+mtopMargin;
break;
}
setMeasuredDimension(sizeWidth,topMargin);
}
@Override
protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
int leftMargin = mleftMargin;
int topMargin = mtopMargin;
for (int j = 0; j < getChildCount(); j++) {
int measuredWidth = getChildAt(j).getMeasuredWidth();
int measuredHeight = getChildAt(j).getMeasuredHeight();
if (leftMargin+measuredWidth+mleftMargin>getWidth()){
leftMargin=mleftMargin;
topMargin+=measuredHeight+mtopMargin;
getChildAt(j).layout(leftMargin,topMargin,leftMargin+measuredWidth,topMargin+measuredHeight);
}else {
getChildAt(j).layout(leftMargin,topMargin,leftMargin+measuredWidth,topMargin+measuredHeight);
}
leftMargin+=measuredWidth+mleftMargin;
}
}
}
布局 activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.bwie.main.yk_001.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/shape"
android:orientation="horizontal">
<FrameLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<EditText
android:id="@+id/edt"
android:textColorHighlight="#ff44ff"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入搜索内容" />
</FrameLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:id="@+id/but"
android:background="#808080"
android:textSize="20dp"
android:text="搜索" />
</LinearLayout>
<com.bwie.main.yk_001.CustomView
android:id="@+id/afl_cotent"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
shape.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#C0C0C0" />
<stroke
android:width="1dip"
android:color="#C0C0C0" />
<padding
android:bottom="5dp"
android:left="12dp"
android:right="12dp"
android:top="5dp" />
<corners android:radius="80dp" />
</shape>
sub_item.xml
<?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="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv_attr_tag"
android:layout_margin="10dp"
android:background="@drawable/shape"
/>
</LinearLayout>
代码页面MainActivity
public class MainActivity extends AppCompatActivity {
private EditText edt;
private Button but;
private CustomView afl_cotent;
private LayoutInflater layoutInflater;
private TextView tvAttrTag;
private List<String> list2 = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
edt = findViewById(R.id.edt);
but = findViewById(R.id.but);
afl_cotent = findViewById(R.id.afl_cotent);
layoutInflater = LayoutInflater.from(this);
//点击搜索按钮添加到历史记录
but.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//获取输入框内容
String s = edt.getText().toString();
//判断输入框内容不可为空
if (!TextUtils.isEmpty(s)){
View item = layoutInflater.inflate(R.layout.sub_item, null);
tvAttrTag = item.findViewById(R.id.tv_attr_tag);
list2.add(s);
for (int i = 0; i < list2.size(); i++) {
tvAttrTag.setText(list2.get(i));
}
afl_cotent.addView(item);
//点击流式布局跳转购物车页面
afl_cotent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,ShoppActivity.class));
finish();
}
});
}
}
});
}
}
新建构物车页面
布局
activity_shopp.xml
<?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.bwie.main.yk_001.ShoppActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
>
<TextView
android:onClick="returntt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="返回"
android:textSize="18dp"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="9"
android:gravity="center"
android:text="购物车"
android:textSize="25dp"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#909090"/>
<android.support.v7.widget.RecyclerView
android:id="@+id/carGV"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="8" />
<RelativeLayout
android:id="@+id/cart_bottom_layout"
android:padding="5dp"
android:background="#AAAAAA"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<CheckBox
android:layout_centerVertical="true"
android:id="@+id/allCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/totalpriceTv"
android:textColor="#ffffff"
android:layout_centerVertical="true"
android:layout_toRightOf="@+id/allCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="总价:"/>
<Button
android:id="@+id/buy"
android:layout_alignParentRight="true"
android:text="去结算"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
</LinearLayout>
jia_jian_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="horizontal"
android:background="@drawable/jia_jian_bg">
<TextView
android:id="@+id/jian"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-"
android:textSize="25sp"
android:padding="5dp"/>
<View
android:layout_width="1px"
android:layout_height="match_parent"
android:background="#999999"/>
<EditText
android:id="@+id/num"
android:layout_weight="1"
android:text="10"
android:gravity="center"
android:background="#00000000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<View
android:layout_width="1px"
android:layout_height="match_parent"
android:background="#999999"/>
<TextView
android:id="@+id/jia"
android:textSize="25sp"
android:padding="5dp"
android:text="+"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
shop_item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:orientation="horizontal">
<CheckBox
android:id="@+id/sellerCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/sellerNameTv"
android:text="商家"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#999999"/>
<android.support.v7.widget.RecyclerView
android:id="@+id/productXRV"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
product_item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:orientation="horizontal">
<CheckBox
android:id="@+id/productCheckbox"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:src="@mipmap/ic_launcher"
android:id="@+id/product_icon"
android:layout_width="80dp"
android:layout_height="80dp"/>
</LinearLayout>
<LinearLayout
android:layout_marginLeft="10dp"
android:layout_width="match_parent"
android:layout_gravity="center"
android:layout_height="wrap_content" android:orientation="vertical">
<TextView
android:id="@+id/title"
android:text="商品标题"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<RelativeLayout
android:layout_marginTop="15dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/price"
android:layout_alignParentLeft="true"
android:text="优惠价:¥99.99"
android:textColor="@android:color/holo_red_light"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<com.bwie.main.yk_001.common.MyJIaJianView
android:id="@+id/jiajianqi"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#999999"/>
</LinearLayout>
jia_jian_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#ffffff"/>
<size android:width="100dp" android:height="30dp"/>
<stroke android:width="1px" android:color="#999999"/>
</shape>
代码页面
ShoppActivity
public class ShoppActivity extends AppCompatActivity implements ShopView, ShopAllCheckboxListener {
private ShopPresenter shopPresenter;
private RecyclerView xRecyclerView;
private ShopAdapter shopAdapter;
private List<ShopBean.DataBean> list;
private CheckBox allCheckbox;
private double totalprice = 0;
private TextView totalpriceTv;
private int page = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopp);
initView();
initData();
}
//初始化
private void initView() {
list = new ArrayList<>();
xRecyclerView = findViewById(R.id.carGV);
allCheckbox = findViewById(R.id.allCheckbox);
totalpriceTv = findViewById(R.id.totalpriceTv);
//设置布局的列表样式
xRecyclerView.setLayoutManager(new LinearLayoutManager(this));
shopAdapter = new ShopAdapter(this,list);
shopAdapter.setShopAllCheckboxListener(this);
//设置点击事件
allCheckbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (allCheckbox.isChecked()){
if (list != null && list.size() >0){
for (int i = 0; i < list.size(); i++) {
list.get(i).setSelected(true);
for (int i1 = 0; i1 < list.get(i).getList().size(); i1++) {
list.get(i).getList().get(i1).setSelected(true);
}
}
}
}else {
if (list != null && list.size() > 0){
for (int i = 0; i < list.size(); i++) {
list.get(i).setSelected(false);
for (int i1 = 0; i1 < list.get(i).getList().size(); i1++) {
list.get(i).getList().get(i1).setSelected(false);
}
}
}
totalprice = 0;
}
//刷新展示列表
shopAdapter.notifyDataSetChanged();
totalprice();
}
});
}
private void initData() {
//请求数据
HashMap<String,String> params = new HashMap<>();
params.put("uid","71");
params.put("page",page+"");
shopPresenter = new ShopPresenter(this);
shopPresenter.getCarts(params,Constants.GETCARTS);
}
//返回按钮
public void returntt(View view) {
startActivity(new Intent(ShoppActivity.this,MainActivity.class));
finish();
}
//请求成功,刷新购物车
@Override
public void success(final ShopBean shopBean) {
List<ShopBean.DataBean> data = shopBean.getData();
list.addAll(data);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (page == 1){
//展示列表数据
shopAdapter = new ShopAdapter(ShoppActivity.this,list);
xRecyclerView.setAdapter(shopAdapter);
}else {
if (shopAdapter != null){
shopAdapter.addPageData(shopBean.getData());
}
}
shopAdapter.setShopAllCheckboxListener(ShoppActivity.this);
}
});
}
//请求失败
@Override
public void failure(String msg) {
Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
}
//总价按钮是否选中的回调
@Override
public void notifyAllCheckboxStatus() {
StringBuilder stringBuilder = new StringBuilder();
if (stringBuilder != null) {
for (int i = 0; i < shopAdapter.getShoplist().size(); i++) {
stringBuilder.append(shopAdapter.getShoplist().get(i).isSelected());
for (int i1 = 0 ; i1 < shopAdapter.getShoplist().get(i).getList().size();i1 ++){
stringBuilder.append(shopAdapter.getShoplist().get(i).getList().get(i1).isSelected());
}
}
}
if (stringBuilder.toString().contains("false")){
allCheckbox.setChecked(false);
totalprice = 0;
}else{
allCheckbox.setChecked(true);
}
//计算总价的方法
totalprice();
}
//计算总价
private void totalprice() {
double totalprice = 0 ;
for (int i = 0; i < shopAdapter.getShoplist().size(); i++) {
for (int i1 = 0; i1 < shopAdapter.getShoplist().get(i).getList().size(); i1++) {
if (shopAdapter.getShoplist().get(i).getList().get(i1).isSelected()){
ShopBean.DataBean.ListBean listBean = shopAdapter.getShoplist().get(i).getList().get(i1);
totalprice+=listBean.getBargainPrice()*listBean.getTotalNum();
}
}
}
totalpriceTv.setText("总价:¥"+totalprice);
}
}
ShopView
public interface ShopView {
//请求成功
void success(ShopBean shopBean);
//请求失败
void failure(String msg);
}
OKHttpUtil
public class OKHttpUtil {
private static OKHttpUtil okHttpUtil;
private OkHttpClient okHttpClient;
private static final String TAG = "OKHttpUtil";
public static OKHttpUtil getInstance() {
if(okHttpUtil == null){
synchronized (OKHttpUtil.class){
if(okHttpUtil == null){
okHttpUtil = new OKHttpUtil();
}
}
}
return okHttpUtil;
}
private OKHttpUtil() {
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient = new OkHttpClient
.Builder()
.addInterceptor(httpLoggingInterceptor)
.connectTimeout(5,TimeUnit.SECONDS)
.writeTimeout(5,TimeUnit.SECONDS)
.readTimeout(5,TimeUnit.SECONDS)
.build();
}
//get封装
public void getData(String url, HashMap<String,String> params, final RequestCallback requestCallback){
StringBuilder stringBuilder = new StringBuilder();
String allUrl = "";
for (Map.Entry<String, String> stringStringEntry : params.entrySet()) {
stringBuilder.append("?").append(stringStringEntry.getKey()).append("=").append(stringStringEntry.getValue()).append("&");
}
allUrl = url+stringBuilder.toString().substring(0,allUrl.length()-1);
Log.d(TAG, "getData: "+allUrl);
final Request request = new Request.Builder()
.url(allUrl)
.get()
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
if(requestCallback != null){
requestCallback.failure(call,e);
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(requestCallback != null){
requestCallback.onResponse(call,response);
}
}
});
}
//post请求
public void postData(String url, HashMap<String,String> params, final RequestCallback requestCallback){
FormBody.Builder builder = new FormBody.Builder();
if(params != null && params.size()>0){
for (Map.Entry<String, String> stringStringEntry : params.entrySet()) {
builder.add(stringStringEntry.getKey(),stringStringEntry.getValue());
}
}
final Request request = new Request.Builder()
.url(url)
.post(builder.build())
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
if(requestCallback != null){
requestCallback.failure(call,e);
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(requestCallback != null){
requestCallback.onResponse(call,response);
}
}
});
}
//封装上传文件
public void uploadFile(String url, HashMap<String, Integer> params, final RequestCallback requestCallback){
//多表单上传的请求体对象,multipart/form-data
MultipartBody.Builder builder = new MultipartBody.Builder();
//设置上传类型是表单形式
builder.setType(MultipartBody.FORM);
for (Map.Entry<String, Integer> stringObjectEntry : params.entrySet()) {
String key = stringObjectEntry.getKey();
Object value = stringObjectEntry.getValue();
if(value instanceof File){
File file = (File) value;
//创建文件请求体
RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
builder.addFormDataPart(key,((File) value).getName(),requestBody);
}else {
builder.addFormDataPart(key, (String) value);
}
}
final Request request = new Request.Builder().addHeader("", "").post(builder.build()).url(url).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
if(requestCallback != null){
requestCallback.failure(call,e);
}
URLEncoder.encode("url");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(requestCallback != null){
requestCallback.onResponse(call,response);
}
}
});
}
public interface RequestCallback{
void onResponse(Call call, Response response);
void failure(Call call, IOException e);
}
}
ShopPresenter
public class ShopPresenter {
private ShopModel shopModel;
private ShopView shopView;
public ShopPresenter(ShopView shopView) {
shopModel= new ShopModel();
attachView(shopView);
}
//绑定view到presenter
private void attachView(ShopView shopView) {
this.shopView = shopView;
}
public void getCarts(HashMap<String,String> params,String url){
shopModel.getShop(params, url, new ShopModel.ShopCallback() {
@Override
public void success(ShopBean shopBean) {
if (shopView != null){
shopView.success(shopBean);
}
}
@Override
public void fail(String msg) {
if (shopView != null){
shopView.failure(msg);
}
}
});
}
//解绑,避免内存泄漏
public void detachView(){
this.shopView = null;
}
}
ShopModel
public class ShopModel {
//请求购物车数据
public void getShop(HashMap<String, String> params, String url, final ShopCallback shopCallback) {
OKHttpUtil.getInstance().postData(url, params, new OKHttpUtil.RequestCallback() {
@Override
public void onResponse(Call call, Response response) {
try {
String jsonResult = response.body().string();
if (!TextUtils.isEmpty(jsonResult)){
parseResult(jsonResult, shopCallback);
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void failure(Call call, IOException e) {
if (shopCallback != null){
shopCallback.fail("网络有异常,请稍后再试");
}
}
});
}
//解析购物车
private void parseResult(String jsonResult, ShopCallback shopCallback) {
ShopBean shopBean = new Gson().fromJson(jsonResult,ShopBean.class);
if (shopCallback != null && shopBean != null){
shopCallback.success(shopBean);
}
}
public interface ShopCallback{
//回调bean对象给presenter
void success(ShopBean shopBean);
//导常信息回调
void fail(String msg);
}
}
CheckListener
//接口回调,父与子之间的回调
public interface CheckListener {
void notifyParent();
}
Constants
public class Constants {
//获取购物车
public static final String GETCARTS= "http://www.zhaoapi.cn/product/getCarts";
}
MyJIaJianView
public class MyJIaJianView extends LinearLayout{
private TextView jiaTv,jiantv;
private EditText numEt;
private int num = 1;
public MyJIaJianView(Context context) {
this(context,null);
}
public MyJIaJianView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public MyJIaJianView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
//初始化自定义的布局
private void init(Context context) {
View view = LayoutInflater.from(context).inflate(R.layout.jia_jian_layout,this,true);
jiantv = view.findViewById(R.id.jian);
jiaTv = view.findViewById(R.id.jia);
numEt = view.findViewById(R.id.num);
numEt.setText(num+"");
jiaTv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
num++;
numEt.setText(num+"");
if (jiaJianListener!=null){
jiaJianListener.getNum(num);
}
}
});
jiantv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
num--;
if (num<=0){
Toast.makeText(getContext(), "数量不能小于1", Toast.LENGTH_SHORT).show();
num = 1;
}
numEt.setText(num+"");
if (jiaJianListener!=null){
jiaJianListener.getNum(num);
}
}
});
}
public void setNumEt(int n) {
numEt.setText(n+"");
num = Integer.parseInt(numEt.getText().toString());
}
private JiaJianListener jiaJianListener;
public void setJiaJianListener(JiaJianListener jiaJianListener) {
this.jiaJianListener = jiaJianListener;
}
public interface JiaJianListener{
void getNum(int num);
}
}
ShopAllCheckboxListener
//接口回调全选 反选
public interface ShopAllCheckboxListener {
void notifyAllCheckboxStatus();
}
ShopBean
父类
public static class DataBean {
//手机添加复选框状态值一级的
private boolean isSelected = false;
public boolean isSelected(){
return isSelected;
}
public void setSelected(boolean selected){
isSelected = selected;
}
子类
public static class ListBean {
//手机添加复选框状态值一级的
private boolean isSelected = false;
public boolean isSelected(){
return isSelected;
}
public void setSelected(boolean selected){
isSelected = selected;
}
//加减器的数量
private int totalNum = 1;
public int getTotalNum(){
return totalNum;
}
public void setTotalNum(int totalNum){
this.totalNum = totalNum;
}
ShopAdapter
public class ShopAdapter extends RecyclerView.Adapter<ShopAdapter.ShopViewHolder> implements CheckListener,ShopAllCheckboxListener{
private Context ccontext;
private List<ShopBean.DataBean> shoplist;
public ShopAdapter(Context context, List<ShopBean.DataBean> list){
ccontext = context;
shoplist =list;
}
public void addPageData(List<ShopBean.DataBean> list){
if (shoplist != null ){
shoplist.addAll(list);
notifyDataSetChanged();
}
}
private CheckBox allCheckbox;
private ShopAllCheckboxListener shopAllCheckboxListener;
//给购物车页面进行回调
public void setShopAllCheckboxListener(ShopAllCheckboxListener shopAllCheckboxListener) {
this.shopAllCheckboxListener = shopAllCheckboxListener;
}
@NonNull
@Override
public ShopViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(ccontext).inflate(R.layout.shop_item_layout,parent,false);
ShopViewHolder shopViewHolder = new ShopViewHolder(itemView);
return shopViewHolder;
}
@Override
public void onBindViewHolder(@NonNull final ShopViewHolder holder, int position) {
final ShopBean.DataBean bean = shoplist.get(position);
holder.nameTv.setText(bean.getSellerName());
//根据bean里的复选框,设置选中状态
holder.checkBox.setChecked(bean.isSelected());
holder.productXRV.setLayoutManager(new LinearLayoutManager(ccontext));
final ProductAdapter productAdapter = new ProductAdapter(ccontext,bean.getList());
holder.productXRV.setAdapter(productAdapter);
productAdapter.setCheckListener(this);
for (int i = 0; i < bean.getList().size(); i++) {
if (!bean.getList().get(i).isSelected()){
holder.checkBox.setChecked(false);
}else{
holder.checkBox.setChecked(true);
}
}
//一级列表的选中状态
holder.checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (holder.checkBox.isChecked()){
bean.setSelected(true);
for (int i = 0; i < bean.getList().size(); i++) {
bean.getList().get(i).setSelected(true);
}
}else {
bean.setSelected(false);
for (int i = 0; i < bean.getList().size(); i++) {
bean.getList().get(i).setSelected(false);
}
}
notifyDataSetChanged();
if (shopAllCheckboxListener != null){
shopAllCheckboxListener.notifyAllCheckboxStatus();
}
}
});
}
//修改之后的集合数据
public List<ShopBean.DataBean> getShoplist(){
return shoplist;
}
@Override
public int getItemCount() {
return shoplist.size() == 0 ? 0 :shoplist.size();
}
//刷新适配器的回调
@Override
public void notifyParent() {
notifyDataSetChanged();
if (shopAllCheckboxListener != null){
shopAllCheckboxListener.notifyAllCheckboxStatus();
}
}
//总价的全选 反选
@Override
public void notifyAllCheckboxStatus() {
for (int i = 0; i < shoplist.size(); i++) {
//父类状态
if (!shoplist.get(i).isSelected()){
allCheckbox.setChecked(true);
break;
}else {
allCheckbox.setChecked(false);
}
//子类状态
for (int i1 = 0; i1 < shoplist.get(i).getList().size(); i1++) {
if (!shoplist.get(i).getList().get(i1).isSelected()){
allCheckbox.setChecked(false);
break;
}
allCheckbox.setChecked(true);
}
}
}
public class ShopViewHolder extends RecyclerView.ViewHolder {
private CheckBox checkBox;
private TextView nameTv;
private RecyclerView productXRV;
public ShopViewHolder(View itemView) {
super(itemView);
checkBox = itemView.findViewById(R.id.sellerCheckbox);
nameTv = itemView.findViewById(R.id.sellerNameTv);
productXRV = itemView.findViewById(R.id.productXRV);
}
}
}
ProductAdapter
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ShopViewHolder>{
private Context ccontext;
private List<ShopBean.DataBean.ListBean> listBeanList;
public ProductAdapter(Context context, List<ShopBean.DataBean.ListBean> list){
ccontext = context;
listBeanList =list;
}
//接口回调引用
private CheckListener checkListener;
public void setCheckListener(CheckListener checkListener) {
this.checkListener = checkListener;
}
private ShopAllCheckboxListener shopAllCheckboxListener;
public void setShopAllCheckboxListener(ShopAllCheckboxListener shopAllCheckboxListener) {
this.shopAllCheckboxListener = shopAllCheckboxListener;
}
@NonNull
@Override
public ShopViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(ccontext).inflate(R.layout.product_item_layout,parent,false);
ShopViewHolder shopViewHolder = new ShopViewHolder(itemView);
return shopViewHolder;
}
@Override
public void onBindViewHolder(@NonNull final ShopViewHolder holder, int position) {
final ShopBean.DataBean.ListBean bean = listBeanList.get(position);
holder.priceTv.setText("优惠价:¥"+bean.getBargainPrice());
holder.titleTv.setText(bean.getTitle());
//分割images,得到图片数组
String[] imgs = bean.getImages().split("\\|");
//校验数组大小是否>0,防止空指针
if (imgs != null && imgs.length > 0){
Glide.with(ccontext).load(imgs[0]).into(holder.productIv);
}else {
holder.productIv.setImageResource(R.mipmap.ic_launcher);
}
holder.checkBox.setChecked(bean.isSelected());
holder.jiajianqi.setNumEt(bean.getTotalNum());
holder.jiajianqi.setJiaJianListener(new MyJIaJianView.JiaJianListener() {
@Override
public void getNum(int num) {
bean.setTotalNum(num);
if (checkListener != null){
checkListener.notifyParent();
}
}
});
//子类选中,并改变父类的状态
holder.checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (holder.checkBox.isChecked()){
//选中
bean.setSelected(true);
}else{
//非选中
bean.setSelected(false);
}
if (checkListener != null){
//刷新父类
checkListener.notifyParent();
}
}
});
}
@Override
public int getItemCount() {
return listBeanList.size() == 0 ? 0 :listBeanList.size();
}
public class ShopViewHolder extends RecyclerView.ViewHolder {
private CheckBox checkBox;
private TextView titleTv,priceTv;
private ImageView productIv;
private MyJIaJianView jiajianqi;
public ShopViewHolder(View itemView) {
super(itemView);
checkBox = itemView.findViewById(R.id.productCheckbox);
titleTv = itemView.findViewById(R.id.title);
priceTv = itemView.findViewById(R.id.price);
productIv = itemView.findViewById(R.id.product_icon);
jiajianqi = itemView.findViewById(R.id.jiajianqi);
}
}
}