首先导入依赖
implementation ‘com.android.support:recyclerview-v7:28.0.0’ implementation ‘com.github.bumptech.glide:glide:4.8.0’
implementation ‘com.google.code.gson:gson:2.8.5’
implementation ‘com.squareup.okhttp3:okhttp:3.12.0’
implementation ‘com.youth.banner:banner:1.4.10’
加入权限
布局文件
activity_main
<android.support.v7.widget.RecyclerView
android:id="@+id/left_recy"
android:layout_width="100dp"
android:layout_height="match_parent"
android:background="@color/gray">
</android.support.v7.widget.RecyclerView>
<android.support.v7.widget.RecyclerView
android:id="@+id/right_recy"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="70dp">
<ImageView
android:id="@+id/shop_car"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:src="@drawable/gouwuc_r"/>
<TextView
android:id="@+id/goods_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="价格:"
android:layout_marginLeft="20dp"
android:layout_centerVertical="true"/>
<TextView
android:id="@+id/goods_num"
android:layout_width="30dp"
android:layout_height="30dp"
android:textSize="10sp"
android:gravity="center"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:background="@drawable/cire_red"
android:textColor="@color/white"
android:text="7"/>
</RelativeLayout>
left_item
right_item
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_toRightOf="@+id/image"
android:padding="10dp"
android:text="aaa" />
<TextView
android:id="@+id/text_price"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/text"
android:layout_marginTop="5dp"
android:layout_toRightOf="@+id/image"
android:padding="10dp"
android:text="价格" />
<com.lll.dc_lx.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.lll.dc_lx.AddSubLayout>
加减器(car_add_sub_layout)
横向布局
<TextView
android:id="@+id/text_number"
android:layout_width="60dp"
android:layout_height="30dp"
android:gravity="center"
android:textSize="14sp"
android:text="1000" />
<TextView
android:id="@+id/btn_sub"
android:layout_width="30dp"
android:layout_height="30dp"
android:textSize="20sp"
android:focusable="false"
android:gravity="center"
android:background="@drawable/car_btn_bg"
android:text="-" />
cire_red样式布局
<?xml version="1.0" encoding="utf-8"?><solid
android:color="#D81B60"></solid>
car_btn_bg样式布局
<?xml version="1.0" encoding="utf-8"?>
代码
MainActivity页面
package com.lll.dc_lx;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.lll.dc_lx.adapter.LeftAdapter;
import com.lll.dc_lx.adapter.RightAdapter;
import com.lll.dc_lx.bean.Goods;
import com.lll.dc_lx.bean.Result;
import com.lll.dc_lx.bean.Shop;
import com.lll.dc_lx.core.BasePresenter;
import com.lll.dc_lx.core.DataCall;
import com.lll.dc_lx.presenter.CartPresenter;
import java.util.List;
public class MainActivity extends AppCompatActivity implements DataCall<List> {
private RecyclerView left_recy;
private RecyclerView right_recy;
private TextView mSumPrice;
private TextView mCount;
private LeftAdapter leftAdapter;
private RightAdapter rightAdapter;
private CartPresenter cartPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
left_recy = findViewById(R.id.left_recy);
right_recy = findViewById(R.id.right_recy);
mSumPrice = findViewById(R.id.goods_price);
mCount = findViewById(R.id.goods_num);
cartPresenter = new CartPresenter(this);
left_recy.setLayoutManager(new LinearLayoutManager(this));
right_recy.setLayoutManager(new LinearLayoutManager(this));
//创建适配器
leftAdapter = new LeftAdapter();
rightAdapter = new RightAdapter();
leftAdapter.setOnItemClickListenter(new LeftAdapter.OnItemClickListenter() {
@Override
public void onItemClick(Shop shop) {
rightAdapter.clearList();//清空数据
rightAdapter.addAll(shop.getList());
rightAdapter.notifyDataSetChanged();
}
});
left_recy.setAdapter(leftAdapter);
rightAdapter.setOnNumListener(new RightAdapter.OnNumListener() {
@Override
public void onNum() {
calculatePrice(leftAdapter.getList());
}
});
right_recy.setAdapter(rightAdapter);
cartPresenter.requestData();
}
private void calculatePrice(List<Shop> list) {
double totalPrice=0;
int totalNum = 0;
for (int i = 0; i < list.size(); i++) {//循环的商家
Shop shop = list.get(i);
for (int j = 0; j < shop.getList().size(); j++) {
Goods goods = shop.getList().get(j);
//计算价格
totalPrice = totalPrice + goods.getNum() * goods.getPrice();
totalNum+=goods.getNum();//计数
}
}
mSumPrice.setText("价格:"+totalPrice);
mCount.setText(""+totalNum);
}
@Override
public void success(List<Shop> data) {
calculatePrice(data);//计算价格和数量
leftAdapter.addAll(data);//左边的添加类型
//得到默认选中的shop,设置上颜色和背景
Shop shop = data.get(1);
shop.setTextColor(0xff000000);
shop.setBackground(R.color.white);
rightAdapter.addAll(shop.getList());
leftAdapter.notifyDataSetChanged();
rightAdapter.notifyDataSetChanged();
}
@Override
public void fail(Result result) {
Toast.makeText(this, result.getCode() + " " + result.getMsg(), Toast.LENGTH_LONG).show();
}
}
AddSubLayout页面
package com.lll.dc_lx;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class AddSubLayout extends LinearLayout implements View.OnClickListener {
private TextView mAddBtn;
private TextView mSubBtn;
private TextView mNumText;
private AddSubListener addSubListener;
public AddSubLayout(Context context) {
super(context);
init();
}
public AddSubLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public AddSubLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
View view = View.inflate(getContext(), R.layout.car_add_sub_layout, this);
mAddBtn = view.findViewById(R.id.btn_add);
mSubBtn = view.findViewById(R.id.btn_sub);
mNumText = view.findViewById(R.id.text_number);
mAddBtn.setOnClickListener(this);
mSubBtn.setOnClickListener(this);
}
@Override
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);
}
}
@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();
}
public void setCount(int count) {
mNumText.setText(count+"");
}
public void setAddSubListener(AddSubListener addSubListener) {
this.addSubListener = addSubListener;
}
public interface AddSubListener{
void addSub(int count);
}
}
p层
CartPresenter页面
package com.lll.dc_lx.presenter;
import com.lll.dc_lx.bean.Result;
import com.lll.dc_lx.core.BasePresenter;
import com.lll.dc_lx.core.DataCall;
import com.lll.dc_lx.model.CarModel;
public class CartPresenter extends BasePresenter {
public CartPresenter(DataCall dataCall) {
super(dataCall);
}
@Override
protected Result getData(Object... args) {
Result result = CarModel.goodsList();//调用网络请求获取数据
return result;
}
}
model层
CarModel页面
package com.lll.dc_lx.model;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lll.dc_lx.bean.Result;
import com.lll.dc_lx.bean.Shop;
import com.lll.dc_lx.http.HttpUtils;
import java.lang.reflect.Type;
import java.util.List;
public class CarModel {
public static Result goodsList() {
String resultString = HttpUtils.get(“http://www.zhaoapi.cn/product/getCarts?uid=71”);
//开始解析
Gson gson = new Gson();
Type type = new TypeToken<Result<List>>() {
}.getType();
Result result = gson.fromJson(resultString, type);
return result;
}
}
Http层
HttpUtils页面
package com.lll.dc_lx.http;
import android.util.Log;
import java.io.File;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class HttpUtils {
public static String get(String s) {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(s).get().build();
try {
Response response = okHttpClient.newCall(request).execute();
String result = response.body().string();
Log.i("dt","请求结果:"+result);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static String postForm(String url,String[] name,String[] value){
OkHttpClient okHttpClient = new OkHttpClient();
FormBody.Builder formBuild = new FormBody.Builder();
for (int i = 0; i < name.length; i++) {
formBuild.add(name[i],value[i]);
}
Request request = new Request.Builder().url(url).post(formBuild.build()).build();
try {
Response response = okHttpClient.newCall(request).execute();
String result = response.body().string();
Log.i("dt",result);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static String postFile(String url,String[] name,String[] value,String fileParamName,File file){
OkHttpClient okHttpClient = new OkHttpClient();
MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
if(file != null){
// MediaType.parse() 里面是上传的文件类型。
RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
String filename = file.getName();
// 参数分别为: 文件参数名 ,文件名称 , RequestBody
requestBody.addFormDataPart(fileParamName, "jpg", body);
}
if (name!=null) {
for (int i = 0; i < name.length; i++) {
requestBody.addFormDataPart(name[i], value[i]);
}
}
Request request = new Request.Builder().url(url).post(requestBody.build()).build();
try {
Response response = okHttpClient.newCall(request).execute();
if (response.code()==200) {
return response.body().string();
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static String postJson(String url,String jsonString){
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),jsonString);
Request request = new Request.Builder().url(url).post(requestBody).build();
try {
Response response = okHttpClient.newCall(request).execute();
return response.body().string();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
Adapter层
LeftAdapter页面
package com.lll.dc_lx.adapter;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.lll.dc_lx.R;
import com.lll.dc_lx.bean.Shop;
import java.util.ArrayList;
import java.util.List;
public class LeftAdapter extends RecyclerView.Adapter<LeftAdapter.MyHolder> {
List mList = new ArrayList<>();
public void addAll(List<Shop> list) {
mList.addAll(list);
}
@NonNull
@Override
public MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = View.inflate(viewGroup.getContext(), R.layout.left_item, null);
MyHolder myHolder = new MyHolder(view);
return myHolder;
}
@Override
public void onBindViewHolder(@NonNull MyHolder myHolder, int i) {
final Shop shop = mList.get(i);
myHolder.text.setText(shop.getSellerName());
myHolder.text.setBackgroundResource(shop.getBackground());
myHolder.text.setTextColor(shop.getTextColor());
myHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for (int j = 0; j <mList.size() ; j++) {
mList.get(j).setTextColor(0xffffffff);
mList.get(j).setBackground(R.color.grayblack);
}
shop.setBackground(R.color.white);
shop.setTextColor(0xff000000);
notifyDataSetChanged();
onItemClickListenter.onItemClick(shop);//切换右边的列表
}
});
}
@Override
public int getItemCount() {
return mList.size();
}
public class MyHolder extends RecyclerView.ViewHolder {
private final TextView text;
public MyHolder(@NonNull View itemView) {
super(itemView);
text = itemView.findViewById(R.id.left_text);
}
}
public List<Shop> getList() {
return mList;
}
private OnItemClickListenter onItemClickListenter;
public void setOnItemClickListenter(OnItemClickListenter onItemClickListenter) {
this.onItemClickListenter = onItemClickListenter;
}
public interface OnItemClickListenter{
void onItemClick(Shop shop);
}
}
RightAdapter页面
package com.lll.dc_lx.adapter;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.lll.dc_lx.AddSubLayout;
import com.lll.dc_lx.R;
import com.lll.dc_lx.bean.Goods;
import com.lll.dc_lx.core.LVApplication;
import java.util.ArrayList;
import java.util.List;
public class RightAdapter extends RecyclerView.Adapter<RightAdapter.ChildHolder> {
private List<Goods> mList = new ArrayList<>();
public void addAll(List<Goods> list) {
mList.addAll(list);
}
@NonNull
@Override
public RightAdapter.ChildHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
View view = View.inflate(viewGroup.getContext(), R.layout.right_item, null);
ChildHolder myHolder = new ChildHolder(view);
return myHolder;
}
@Override
public void onBindViewHolder(@NonNull RightAdapter.ChildHolder childHolder, int position) {
final Goods goods = mList.get(position);
childHolder.text.setText(goods.getTitle());
childHolder.price.setText("单价:" + goods.getPrice());//单价
String imageurl = "https" + goods.getImages().split("https")[1];
Log.i("dt", "imageUrl: " + imageurl);
imageurl = imageurl.substring(0, imageurl.lastIndexOf(".jpg") + ".jpg".length());
Glide.with(LVApplication.getInstance()).load(imageurl).into(childHolder.image);//加载图片
childHolder.addSub.setCount(goods.getNum());//设置商品数量
childHolder.addSub.setAddSubListener(new AddSubLayout.AddSubListener() {
@Override
public void addSub(int count) {
goods.setNum(count);
onNumListener.onNum();//计算价格
}
});
}
@Override
public int getItemCount() {
return mList.size();
}
public void clearList() {
mList.clear();
}
class ChildHolder extends RecyclerView.ViewHolder {
TextView text;
TextView price;
ImageView image;
AddSubLayout addSub;
public ChildHolder(@NonNull View itemView) {
super(itemView);
text = itemView.findViewById(R.id.text);
price = itemView.findViewById(R.id.text_price);
image = itemView.findViewById(R.id.image);
addSub = itemView.findViewById(R.id.add_sub_layout);
}
}
private OnNumListener onNumListener;
public void setOnNumListener(OnNumListener onNumListener) {
this.onNumListener = onNumListener;
}
public interface OnNumListener{
void onNum();
}
}
Bean层
Goods页面
package com.lll.dc_lx.bean;
import java.io.Serializable;
public class Goods implements Serializable {
// “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.0,
// “pscid”: 1,
// “salenum”: 0,
// “sellerid”: 17,
// “subhead”: “每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下”,
// “title”: “北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g”
private double bargainPrice;
private String createtime;
private String detailUrl;
private String images;
private int num;
private int pid;
private double price;
private int pscid;
private int selected;
private int sellerid;
private String subhead;
private String title;
private int count=1;
public void setCount(int count) {
this.count = count;
}
public int getCount() {
return count;
}
public double getBargainPrice() {
return bargainPrice;
}
public void setBargainPrice(double bargainPrice) {
this.bargainPrice = bargainPrice;
}
public String getCreatetime() {
return createtime;
}
public void setCreatetime(String createtime) {
this.createtime = createtime;
}
public String getDetailUrl() {
return detailUrl;
}
public void setDetailUrl(String detailUrl) {
this.detailUrl = detailUrl;
}
public String getImages() {
return images;
}
public void setImages(String images) {
this.images = images;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getPscid() {
return pscid;
}
public void setPscid(int pscid) {
this.pscid = pscid;
}
public int getSelected() {
return selected;
}
public void setSelected(int selected) {
this.selected = selected;
}
public int getSellerid() {
return sellerid;
}
public void setSellerid(int sellerid) {
this.sellerid = sellerid;
}
public String getSubhead() {
return subhead;
}
public void setSubhead(String subhead) {
this.subhead = subhead;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Result页面
package com.lll.dc_lx.bean;
public class Result {
int code;
String msg;
T data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
Shop页面
package com.lll.dc_lx.bean;
import com.lll.dc_lx.R;
import java.util.List;
public class Shop {
List list;
String sellerName;
String sellerid;
int textColor = 0xffffffff;
int background = R.color.grayblack;
boolean check;
public List<Goods> getList() {
return list;
}
public void setList(List<Goods> list) {
this.list = list;
}
public String getSellerName() {
return sellerName;
}
public void setSellerName(String sellerName) {
this.sellerName = sellerName;
}
public String getSellerid() {
return sellerid;
}
public void setSellerid(String sellerid) {
this.sellerid = sellerid;
}
public int getTextColor() {
return textColor;
}
public void setTextColor(int textColor) {
this.textColor = textColor;
}
public int getBackground() {
return background;
}
public void setBackground(int background) {
this.background = background;
}
public boolean isCheck() {
return check;
}
public void setCheck(boolean check) {
this.check = check;
}
}
core层
BasePresenter页面
package com.lll.dc_lx.core;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import com.lll.dc_lx.bean.Result;
public abstract class BasePresenter {
DataCall dataCall;
public BasePresenter(DataCall dataCall){
this.dataCall = dataCall;
}
Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
Result result = (Result) msg.obj;
if (result.getCode()==0){
dataCall.success(result.getData());
}else{
dataCall.fail(result);
}
}
};
public void requestData(final Object...args){
new Thread(new Runnable() {
@Override
public void run() {
Message message = mHandler.obtainMessage();
message.obj = getData(args);
mHandler.sendMessage(message);
}
}).start();
}
protected abstract Result getData(Object...args);
public void unBindCall(){
this.dataCall = null;
}
}
DataCall页面
package com.lll.dc_lx.core;
import com.lll.dc_lx.bean.Result;
public interface DataCall {
void success(T data);
void fail(Result result);
}
Application页面
package com.lll.dc_lx.core;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
public class LVApplication extends Application {
private static LVApplication instance;
private SharedPreferences sharedPreferences;
@Override
public void onCreate() {
super.onCreate();
instance = this;
sharedPreferences = getSharedPreferences("application",
Context.MODE_PRIVATE);
// JPushInterface.setDebugMode(true);
// JPushInterface.init(this); // 初始化 JPush
}
public static LVApplication getInstance() {
return instance;
}
public SharedPreferences getShare() {
return sharedPreferences;
}
}