Android——EventBus实现一级购物车

效果图:

实现接口:

 

公共请求参数:source=android

参数名称:source

参数值:android

类型:String

 

http://120.27.23.105/product/searchProducts

keywords=笔记本&page=1

参数说明:

keywords 关键字字段 String类型 必传

page  页码数  String类型  必传

先添加依赖:

 

compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.google.code.gson:gson:2.8.2'
compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'org.greenrobot:eventbus:3.1.1'

 

Okhttp进行网络请求封装:

HttpUtils/**
* Created by Wangrx on 2017/11/21.
*/

public class HttpUtils {
private static final String TAG = "HttpUtils";
private static volatile HttpUtils instance;

private static Handler handler = new Handler();

private HttpUtils() {

}

public static HttpUtils getInstance() {
if (null == instance) {
synchronized (HttpUtils.class) {
if (instance == null) {
instance = new HttpUtils();
}
}
}
return instance;
}
/**
* 封装的post请求
*
* @param url
* @param map
* @param callBack
* @param cls
*/
public void post(String url, Map<String, String> map, final CallBack callBack, final Class cls, final String tag) {
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();

FormBody.Builder builder = new FormBody.Builder();
for (Map.Entry<String, String> entry : map.entrySet()) {
builder.add(entry.getKey(), entry.getValue());
}

FormBody body = builder.build();

final Request request = new Request.Builder()
.url(url)
.post(body)
.build();

Call call = client.newCall(request);
call.enqueue(new okhttp3.Callback() {
@Override
public void onFailure(Call call, final IOException e) {
Log.e(TAG, "onFailure: " + e.getCause().getStackTrace() + e.getMessage());
handler.post(new Runnable() {
@Override
public void run() {
callBack.onFailed(tag,e);
}
});

}

@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
Log.i(TAG, "onResponse: " + result);

final Object o = GsonUtils.getInstance().fromJson(result, cls);
handler.post(new Runnable() {
@Override
public void run() {
callBack.onSuccess(tag,o);
}
});
}
});
}
}

GsonUtils(单例模式)/**
* Created by Wangrx on 2017/11/21.
*/

public class GsonUtils {
private static Gson instance;
private GsonUtils(){

}
public static Gson getInstance(){
if (instance==null){
instance = new Gson();
}
return instance;
}
}

CallBack/**
* Created by Wangrx on 2017/11/21.
*/

public interface CallBack {
void onSuccess(String tag, Object o);
void onFailed(String tag, Exception e);
}

INewsView/**
* Created by Wangrx on 2017/11/21.
*/

public interface INewsView {
void success(String tag, List<JavaBean.DataBean> news);

void failed(String tag, Exception e);
}

LoggingInterceptor(拦截器)/**
* Created by Wangrx on 2017/11/21.
*/

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);
}
}

INewsPresenter(P层)/**
* Created by Wangrx on 2017/11/21.
*/

public class INewsPresenter {
private INewsView inv;

public void attachView(INewsView inv) {
this.inv = inv;
}
public void getNews() {
//type=top&key=dbedecbcd1899c9785b95cc2d17131c5
Map<String, String> map = new HashMap<>();
map.put("keywords", "笔记本");
map.put("page", "1");
HttpUtils.getInstance().post("http://120.27.23.105/product/searchProducts", map, new CallBack() {
@Override
public void onSuccess(String tag, Object o) {
JavaBean bean = (JavaBean) o;
if (bean != null) {
List<JavaBean.DataBean> data = bean.getData();
inv.success(tag, data);
}
}

@Override
public void onFailed(String tag, Exception e) {
inv.failed(tag, e);
}
}, JavaBean.class, "news");
}


public void detachView() {
if (inv != null) {
inv = null;
}

}
}

MainActivitypublic class MainActivity extends AppCompatActivity implements INewsView{

private List<JavaBean.DataBean> list = new ArrayList<>();
private RecyclerView recy_view;
private CheckBox cb_all;
private TextView tv_sum;
private TextView tv_count;
private Button btn_jiesuan;
private ShowAdapter adapter;
private INewsPresenter presenter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();

}

@Override
protected void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}

private void initView() {
recy_view = (RecyclerView) findViewById(R.id.recy_view);
cb_all = (CheckBox) findViewById(R.id.cb_all);
tv_sum = (TextView) findViewById(R.id.tv_sum);
tv_count = (TextView) findViewById(R.id.tv_count);
btn_jiesuan = (Button) findViewById(R.id.btn_jiesuan);
LinearLayoutManager manager = new LinearLayoutManager(this);
recy_view.setLayoutManager(manager);
adapter = new ShowAdapter(this, list);
recy_view.setAdapter(adapter);
presenter = new INewsPresenter();
presenter.attachView(this);
presenter.getNews();
cb_all.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
adapter.changeAllListCbState(cb_all.isChecked());
}
});
}

@Override
public void success(String tag, List<JavaBean.DataBean> news) {
list.addAll(news);
adapter.notifyDataSetChanged();
}

@Override
public void failed(String tag, Exception e) {

}
@Subscribe
public void onMessageEvent(MessageEvent event) {
cb_all.setChecked(event.isChecked());
}

@Subscribe
public void onMessageEvent(PriceAndCountEvent event) {
tv_count.setText("共" + event.getCount() + "件");
tv_sum.setText("¥"+event.getPrice() );
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
if (presenter != null) {
presenter.detachView();
}
}
}

MessageEvent/**
* Created by peng on 2017/11/17.
*/

public class MessageEvent {
private boolean checked;

public boolean isChecked() {
return checked;
}

public void setChecked(boolean checked) {
this.checked = checked;
}
}

PriceAndCountEvent/**
* Created by peng on 2017/11/17.
*/

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;
}
}

ShowAdapter(适配器)/**
* Created by Wangrx on 2017/11/21.
*/

public class ShowAdapter extends RecyclerView.Adapter<ShowAdapter.ViewHolder>{

private Context context;
private List<JavaBean.DataBean> list;


public ShowAdapter(Context context, List<JavaBean.DataBean> list) {
this.context = context;
this.list = list;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = View.inflate(context, R.layout.item, null);
ViewHolder holder = new ViewHolder(view);
return holder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
String[] split = list.get(position).getImages().split("[|]");
Glide.with(context).load(split[0]).into(holder.item_img);
holder.item_price.setText(list.get(position).getPrice()+"");
holder.item_title.setText(list.get(position).getTitle());
holder.et_num.setText(list.get(position).getPid()+"");
holder.item_cb.setChecked(list.get(position).isCheckbox());
holder.child_sum.setText(list.get(position).getPid()*list.get(position).getPrice()+"");
holder.child_num.setText(list.get(position).getPid()+"");
holder.item_cb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
list.get(position).setCheckbox(holder.item_cb.isChecked());
PriceAndCountEvent priceAndCountEvent = compute();
EventBus.getDefault().post(priceAndCountEvent);

if (holder.item_cb.isChecked()) {
changGroupCbState(position, true);
changeAllCbState(isAllGroupCbSelected());
} else {
changGroupCbState(position, false);
changeAllCbState(isAllGroupCbSelected());
}
notifyDataSetChanged();
}
});
//加号
holder.bt_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int num = list.get(position).getPid();
holder.et_num.setText(++num + "");
list.get(position).setPid(num);
holder.child_sum.setText(list.get(position).getPid()*list.get(position).getPrice()+"");
holder.child_num.setText(list.get(position).getPid()+"");
if (holder.item_cb.isChecked()) {
EventBus.getDefault().post(compute());
}
}
});
//减号
holder.bt_reduce.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int num = list.get(position).getPid();
if (num == 1) {
return;
}
holder.et_num.setText(--num + "");
list.get(position).setPid(num);
holder.child_sum.setText(list.get(position).getPid()*list.get(position).getPrice()+"");
holder.child_num.setText(list.get(position).getPid()+"");
if (holder.item_cb.isChecked()) {
EventBus.getDefault().post(compute());
}
}
});
//删除
holder.item_delete.setOnClickListener(new View.OnClickListener() {

private AlertDialog dialog;

@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("提示");
builder.setMessage("确认是否删除?");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
list.remove(position);
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();

}
});


}

@Override
public int getItemCount() {
if (list == null) {
return 0;
}
return list.size();
}

public class ViewHolder extends RecyclerView.ViewHolder{

private final CheckBox item_cb;
private final ImageView item_img;
private final TextView item_title;
private final TextView item_price;

private final TextView child_num;
private final TextView child_sum;
private final Button item_delete;
private final Button bt_add;
private final Button bt_reduce;
private final EditText et_num;

public ViewHolder(View itemView) {
super(itemView);
item_cb = itemView.findViewById(R.id.item_cb);
item_img = itemView.findViewById(R.id.item_img);
item_title = itemView.findViewById(R.id.item_title);
item_price = itemView.findViewById(R.id.item_price);
child_num = itemView.findViewById(R.id.child_num);
child_sum = itemView.findViewById(R.id.child_sum);
item_delete = itemView.findViewById(R.id.item_delete);
bt_add = itemView.findViewById(R.id.bt_add);
bt_reduce = itemView.findViewById(R.id.bt_reduce);
et_num = itemView.findViewById(R.id.et_num);
}
}
/**
* 改变全选的状态
*
* @param flag
*/
private void changeAllCbState(boolean flag) {
MessageEvent messageEvent = new MessageEvent();
messageEvent.setChecked(flag);
EventBus.getDefault().post(messageEvent);
}
/**
* 计算列表中,选中的钱和数量
*/
private PriceAndCountEvent compute() {
int count = 0;
int price = 0;
for (int i = 0; i < list.size(); i++) {
JavaBean.DataBean dataBean = list.get(i);

if (dataBean.isCheckbox()) {
price += dataBean.getPid() * dataBean.getPrice();
count += dataBean.getPid();
}

}
PriceAndCountEvent priceAndCountEvent = new PriceAndCountEvent();
priceAndCountEvent.setCount(count);
priceAndCountEvent.setPrice(price);
return priceAndCountEvent;
}
/**
* 判断一级列表是否全部选中
*
* @return
*/
private boolean isAllGroupCbSelected() {
for (int i = 0; i < list.size(); i++) {
JavaBean.DataBean dataBean = list.get(i);

if (!dataBean.isCheckbox()) {
return false;
}
}
return true;
}
/**
* 改变一级列表checkbox状态
*
* @param groupPosition
*/
private void changGroupCbState(int groupPosition, boolean flag) {
JavaBean.DataBean dataBean = list.get(groupPosition);

dataBean.setCheckbox(flag);
}
/**
* 判断列表是否全部选中
*
*
* @return
*/
private boolean isAllChildCbSelected() {
for (int i = 0;i<list.size();i++){
JavaBean.DataBean dataBean = list.get(i);
if (!dataBean.isCheckbox()) {
return false;
}
}
return true;
}
/**
* 设置全选、反选
*
* @param flag
*/
public void changeAllListCbState(boolean flag) {
for (int i = 0; i < list.size(); i++) {
changGroupCbState(i, flag);
}
EventBus.getDefault().post(compute());
notifyDataSetChanged();
}
}

布局文件:

activity_main.xml<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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="com.bwie.com.myapplication.MainActivity">
<RelativeLayout
android:id="@+id/rel"
android:layout_width="match_parent"
android:layout_height="40dp">
<ImageView
android:id="@+id/img_back"
android:layout_width="30dp"
android:layout_height="30dp"
android:src="@mipmap/left"
android:layout_centerVertical="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="购物车"
android:textSize="20sp"
android:layout_centerInParent="true"
/>
</RelativeLayout>

<RelativeLayout
android:id="@+id/rel2"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="60dp">
<CheckBox
android:id="@+id/cb_all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
/>
<TextView
android:id="@+id/all_xuan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="全选"
android:textSize="20sp"
android:layout_toRightOf="@+id/cb_all"
android:layout_centerVertical="true"
/>
<Button
android:id="@+id/btn_jiesuan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="结算"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
/>

<TextView
android:id="@+id/tvv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="共计(件):"
android:textSize="15sp"
android:layout_toRightOf="@+id/all_xuan"
android:layout_marginLeft="20dp"
/>
<TextView
android:id="@+id/tv_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="15sp"
android:layout_toRightOf="@+id/tvv"
/>

<TextView
android:id="@+id/tvv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="总价(元):"
android:layout_toRightOf="@+id/all_xuan"
android:textSize="15sp"
android:layout_below="@+id/tvv"
android:layout_marginLeft="20dp"
/>
<TextView
android:id="@+id/tv_sum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="20sp"
android:layout_below="@+id/tvv"
android:layout_toRightOf="@+id/tvv2"
/>

</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="@+id/recy_view"
android:layout_above="@id/rel2"
android:layout_below="@+id/rel"
android:layout_width="match_parent"
android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>


</RelativeLayout>

item.xml<?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="match_parent">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="horizontal">

<CheckBox
android:id="@+id/item_cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" />

<ImageView
android:id="@+id/item_img"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher" />

<LinearLayout
android:layout_width="0dp"
android:layout_height="100dp"
android:layout_marginLeft="10dp"
android:layout_weight="5"
android:orientation="vertical">

<TextView
android:id="@+id/item_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:text="标题"
android:textSize="20sp" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:id="@+id/item_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10sp"
android:textSize="16sp"
android:text="单价" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<Button
android:id="@+id/bt_add"
android:layout_width="36dp"
android:layout_height="36dp"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="+"/>

<EditText
android:id="@+id/et_num"
android:layout_width="70dp"
android:layout_height="36dp"
android:inputType="number"
android:gravity="center"
android:focusableInTouchMode="false"
android:focusable="false"
android:text="1"
android:background="@null"
/>
<Button
android:id="@+id/bt_reduce"
android:layout_width="36dp"
android:layout_height="36dp"
android:clickable="false"
android:focusableInTouchMode="false"
android:text="-"/>


</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="共计:"
/>
<TextView
android:id="@+id/child_num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
/>
<TextView
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="总价"
android:layout_marginLeft="10dp"
/>
<TextView
android:id="@+id/child_sum"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0.00"
/>
</LinearLayout>

</LinearLayout>
<Button
android:layout_weight="1"
android:id="@+id/item_delete"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="删除"
android:layout_gravity="center_vertical"
/>
</LinearLayout>

</RelativeLayout>

通过Okhttp网络请求类 获取接口中的数据,p层得到数据,通过接口回调的方式传给M层,在M层将数据传给适配器,在适配器中对购物车进行加减删除的操作,通过EventBus将数据传给M层,通过M层的全选按钮进行操作全选反选,一个简单的购物车就实现了。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值