上个博客的依赖和包
导入图片.颜色
Bean包里
Goods
http://www.zhaoapi.cn/product/getCarts?uid=71
data里的
public class Goods implements Serializable{
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;
}
Result
public class Result<T> {
int code;
String msg;
T data;
}
Shop
public class Shop {
List<Goods> list;
String sellerName;
String sellerid;
int textColor = 0xffffffff;
int background = R.color.grayblack;
boolean check;
Core包里
接口DataCall
public interface DataCall<T> {
void success(T data);
void fail(Result result);
}
BasePresenter
package com.baidu.day20.Core;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import com.baidu.day20.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;
}
}
DTApplication
package com.baidu.day20.Core;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
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);
}
public static DTApplication getInstance(){
return instance;
}
public SharedPreferences getShare(){
return mSharedPreferences;
}
}
Utils
日志拦截
LoggingInterceptor
package com.baidu.day20.Utils;
import android.util.Log;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.Internal;
public class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();//请求发起的时间
Log.i("dt",String.format("发送请求 %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();//收到响应的时间
ResponseBody responseBody = response.peekBody(1024 * 1024);
Log.i("dt",String.format("接收响应: [%s] %n返回json:【%s】 %.1fms%n%s",
response.request().url(),
responseBody.string(),
(t2 - t1) / 1e6d,
response.headers()));
return response;
}
}
GlideImageLoader
public class GlideImageLoader extends ImageLoader {
@Override
public void displayImage(Context context, Object path, ImageView imageView) {
Glide.with(context).load(path).into(imageView);
}
}
HttpUtils
package com.baidu.day20.Utils;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
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 urlString) {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10,TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.build();
Request request = new Request.Builder()
.url(urlString)
.get()
.build();
try {
Response response = okHttpClient.newCall(request).execute();
String result = response.body().string();
Log.i("dt", "请求结果:" + result);
return result;
} catch (IOException 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 (IOException 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.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 (IOException 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 (IOException e) {
e.printStackTrace();
}
return "";
}
}
M层Model
CartModel
package com.baidu.day20.model;
import com.baidu.day20.Utils.HttpUtils;
import com.baidu.day20.bean.Result;
import com.baidu.day20.bean.Shop;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
public class CartModel {
public static Result goodsList() {
String resultString = HttpUtils.get("http://www.zhaoapi.cn/product/getCarts?uid=71");
try {
Gson gson = new Gson();
Type type = new TypeToken<Result<List<Shop>>>() {
}.getType();
Result result = gson.fromJson(resultString, type);
return result;
} catch (Exception e) {
}
Result result = new Result();
result.setCode(-1);
result.setMsg("数据解析异常");
return result;
}
}
P层persenter
CartPresenter
public class CartPresenter extends BasePresenter {
public CartPresenter(DataCall dataCall) {
super(dataCall);
}
@Override
protected Result getData(Object... args) {
Result result = CartModel.goodsList();
return result;
}
}
自定义商品界面
布局
car_add_sub_layout
<?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="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/btn_add"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="@drawable/car_btn_bg"
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:background="@drawable/car_btn_bg"
android:text="-" />
</LinearLayout>
View 里写
AddSubLayout
package com.baidu.day20.View;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.day20.R;
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();
}
public AddSubLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initView();
}
private void initView() {
//加载layout布局,第三个参数ViewGroup一定写成this
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
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);
}
}
布局
cart_item
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@drawable/search_edit_bg"
android:orientation="horizontal">
<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"/>
<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"/>
<com.baidu.mooktesk1.util.view.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.baidu.mooktesk1.util.view.AddSubLayout>
</RelativeLayout>
下面就是饿了么购物车
主页面布局
<?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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<android.support.v7.widget.RecyclerView
android:id="@+id/left_recycler"
android:layout_width="100dp"
android:layout_height="match_parent"
android:background="@color/grayblack">
</android.support.v7.widget.RecyclerView>
<android.support.v7.widget.RecyclerView
android:id="@+id/right_recycler"
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="80dp">
<ImageView
android:id="@+id/shop_car_image"
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_sum_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_number"
android:layout_width="30dp"
android:layout_height="30dp"
android:textSize="10sp"
android:gravity="center"
android:textColor="@color/white"
android:layout_marginLeft="-10dp"
android:background="@drawable/circle_red_bg"
android:layout_alignParentTop="true"
android:layout_toEndOf="@+id/shop_car_image"
android:text="7" />
</RelativeLayout>
</LinearLayout>
recycler_left_item
<?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="match_parent">
<TextView
android:id="@+id/left_text"
android:layout_width="100dp"
android:layout_height="50dp"
android:textSize="16sp"
android:gravity="center"
android:textColor="@color/white"
android:text="aa" />
</LinearLayout>
recycler_right_item
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@drawable/search_edit_bg"
android:orientation="horizontal">
<ImageView
android:id="@+id/image"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:minHeight="50dp"
android:layout_alignParentLeft="true"
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"/>
<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"/>
<com.baidu.mooktesk1.util.view.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.baidu.mooktesk1.util.view.AddSubLayout>
</RelativeLayout>
适配器
LeftAdapter
package com.baidu.day20.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.baidu.day20.R;
import com.baidu.day20.bean.Shop;
import java.util.ArrayList;
import java.util.List;
public class LeftAdapter extends RecyclerView.Adapter<LeftAdapter.MyHolder> {
private List<Shop> 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.recycler_left_item, null);
MyHolder myHolder = new MyHolder(view);
return myHolder;
}
@Override
public void onBindViewHolder(@NonNull final 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 List<Shop> getList() {
return mList;
}
class MyHolder extends RecyclerView.ViewHolder {
TextView text;
public MyHolder(@NonNull View itemView) {
super(itemView);
text = itemView.findViewById(R.id.left_text);
}
}
private OnItemClickListenter onItemClickListenter;
public void setOnItemClickListenter(OnItemClickListenter onItemClickListenter) {
this.onItemClickListenter = onItemClickListenter;
}
public interface OnItemClickListenter {
void onItemClick(Shop shop);
}
}
RightAdapter
package com.baidu.day20.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.baidu.day20.Core.DTApplication;
import com.baidu.day20.R;
import com.baidu.day20.View.AddSubLayout;
import com.baidu.day20.bean.Goods;
import com.bumptech.glide.Glide;
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 ChildHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
View view = View.inflate(viewGroup.getContext(), R.layout.recycler_right_item, null);
ChildHolder myHolder = new ChildHolder(view);
return myHolder;
}
@Override
public void onBindViewHolder(@NonNull 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(DTApplication.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();
}
}
Acitvity
ShopCartActivity
package com.baidu.day20;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.day20.Core.DataCall;
import com.baidu.day20.adapter.LeftAdapter;
import com.baidu.day20.adapter.RightAdapter;
import com.baidu.day20.bean.Goods;
import com.baidu.day20.bean.Result;
import com.baidu.day20.bean.Shop;
import com.baidu.day20.persenter.CartPresenter;
import java.util.List;
public class Main2Activity extends AppCompatActivity implements DataCall<List<Shop>> {
private TextView mSumPrice;
private TextView mCount;
private RecyclerView mLeftRecycler, mRightRecycler;
private LeftAdapter mLeftAdapter;
private RightAdapter mRightAdapter;
private CartPresenter cartPresenter = new CartPresenter(this);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mSumPrice = findViewById(R.id.goods_sum_price);
mCount = findViewById(R.id.goods_number);
mLeftRecycler = findViewById(R.id.left_recycler);
mRightRecycler = findViewById(R.id.right_recycler);
mLeftRecycler.setLayoutManager(new LinearLayoutManager(this));
mRightRecycler.setLayoutManager(new LinearLayoutManager(this));
mLeftAdapter = new LeftAdapter();
mLeftAdapter.setOnItemClickListenter(new LeftAdapter.OnItemClickListenter() {
@Override
public void onItemClick(Shop shop) {
mRightAdapter.clearList();
//清空数据
mRightAdapter.addAll(shop.getList());
mRightAdapter.notifyDataSetChanged();
}
});
mLeftRecycler.setAdapter(mLeftAdapter);
mRightAdapter = new RightAdapter();
mRightAdapter.setOnNumListener(new RightAdapter.OnNumListener() {
@Override
public void onNum() {
calculatePrice(mLeftAdapter.getList());
}
});
mRightRecycler.setAdapter(mRightAdapter);
cartPresenter.requestData();
}
@Override
public void success(List<Shop> data) {
calculatePrice(data);
mLeftAdapter.addAll(data);
Shop shop = data.get(1);
shop.setTextColor(0xff000000);
shop.setBackground(R.color.white);
mRightAdapter.addAll(shop.getList());
mLeftAdapter.notifyDataSetChanged();
mRightAdapter.notifyDataSetChanged();
}
public void fail(Result result) {
Toast.makeText(this, result.getCode() + " " + result.getMsg(), Toast.LENGTH_LONG).show();
}
private void calculatePrice(List<Shop> shopList) {
double totalPrice = 0;
int totalNum = 0;
for (int i = 0; i < shopList.size(); i++) {
Shop shop = shopList.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);
}
}