Android中购物车的全选、反选、问题和计算价格
此Demo主要解决的是购物车中的全选,反选计算价格和选中的条目个数的问题,当选中几条时,点击反选,会把当先选中的变为不选中,把不选中的变为选中。点击全选会全部选中,再次点击时,变为全部不选中。
//-----------一下为main的布局-----------------------
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView android:layout_width="fill_parent"
android:layout_height="40dp"
android:text="已选中个数"
android:id="@+id/tv_num"
android:gravity="center"/>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="40dp"
android:orientation="horizontal"
>
<Button android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="fill_parent"
android:text="全选"
android:gravity="center"
android:id="@+id/bt_quanxuan"/>
<Button android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="fill_parent"
android:text="反选"
android:gravity="center"
android:id="@+id/bt_fanxuan"/>
</LinearLayout>
<ListView android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="@+id/lv"></ListView>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="40dp"
android:orientation="horizontal"
>
<TextView android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="2"
android:text="总价:"
android:id="@+id/tv_zongjai"
android:gravity="center"/>
<Button android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="支付"
android:id="@+id/bt_zifu"
android:gravity="center"/>
</LinearLayout>
</LinearLayout>
//-----------------一下为Listview条目的布局--------------------------------
<?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="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox android:layout_width="60dp"
android:layout_height="wrap_content"
android:gravity="center"
android:id="@+id/cb_checkbox"/>
<TextView android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:id="@+id/tv_title"
android:textSize="20sp"/>
<TextView android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="@+id/tv_money"
android:gravity="center"/>
</LinearLayout>
</LinearLayout>
//------------------一下为bean包中封装的数据对象-----创建了一个News类-----------------------
package com.bwie.test;
public class News {
private String title;
private String money;
private boolean flag;
public News(String title, String money, boolean flag) {
super();
this.title = title;
this.money = money;
this.flag = flag;
}
public News() {
super();
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMoney() {
return money;
}
public void setMoney(String money) {
this.money = money;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public String toString() {
return "News [title=" + title + ", money=" + money + ", flag=" + flag
+ "]";
}
}
//---------------一下是自定义的适配器-------MyAdapter-------------------------
package com.bwie.test;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
public class MyAdapter extends BaseAdapter{
private List<News> news;
private Context context;
private static HashMap<Integer, Boolean> isSelected;
private onCheckListener listener;
private CheckBox check;
public MyAdapter(List<News> news, Context context) {
super();
this.news = news;
this.context = context;
isSelected = new HashMap<Integer, Boolean>();
for (int i = 0; i < news.size(); i++) {
getIsSelected().put(i, false);
}
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return news.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return news.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
News newss=news.get(position);
if (convertView==null) {
convertView=View.inflate(context, R.layout.list_item, null);
holder=new ViewHolder();
holder.title=(TextView) convertView.findViewById(R.id.tv_title);
holder.money=(TextView) convertView.findViewById(R.id.tv_money);
holder.flag=(CheckBox) convertView.findViewById(R.id.cb_checkbox);
convertView.setTag(holder);
}
holder=(ViewHolder) convertView.getTag();
holder.title.setText(newss.getTitle());
holder.money.setText(newss.getMoney());
holder.flag.setChecked(newss.isFlag());
// 根据isSelected来设置checkbox的选中状况
holder.flag.setChecked(getIsSelected().get(position));
holder.flag.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO 自动生成的方法存根
if (isSelected.get(position)) {
isSelected.put(position, false);
setIsSelected(isSelected);
} else {
isSelected.put(position, true);
setIsSelected(isSelected);
}
listener.onCheck(isSelected);
}
});
return convertView;
}
static class ViewHolder{
public TextView title;
public TextView money;
public CheckBox flag;
}
public static HashMap<Integer, Boolean> getIsSelected() {
return isSelected;
}
public static void setIsSelected(HashMap<Integer, Boolean> isSelected) {
MyAdapter.isSelected = isSelected;
}
public void setListener(onCheckListener listener) {
this.listener = listener;
}
public interface onCheckListener {
void onCheck(HashMap<Integer, Boolean> map);
}
}
//--------------------------------------
//========================以下是MainActivity==========================================
package com.bwie.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.bwie.test.MyAdapter.onCheckListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity implements onCheckListener, OnClickListener {
private String urlPath="http://172.17.29.120/localuser/loupengfei/kaoshi/shoppingcar.json";
private List<News> news=new ArrayList<News>();
private ArrayList<Shopbean> list;
private int checkNum = 0; // 记录选中的条目数量
private float total = 0.00f;
private Button bt_fanxuan;
private Button bt_quanxuan;
private MyAdapter adapter;
private TextView tv_num;
private TextView tv_zongjai;
private ListView lv;
private SharedPreferences sp;
private Handler handler=new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
//获得网络请求的数据
String text=(String) msg.obj;
tojson(text);
break;
default:
break;
}
}
};
//------------------------
private void tojson(String text) {
try {
JSONObject obj=new JSONObject(text);
JSONArray data=obj.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject json=data.getJSONObject(i);
String title=json.getString("title");
String money=json.getString("money");
News newss=new News(title, money, false);
news.add(newss);
}
//设置适配器
adapter = new MyAdapter(news, this);
lv.setAdapter(adapter);
adapter.setListener(this);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
//------------------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//创建SharedPreferences
sp = getSharedPreferences("kk", Context.MODE_PRIVATE);
//找到控件
bt_fanxuan = (Button) findViewById(R.id.bt_fanxuan);
bt_quanxuan = (Button) findViewById(R.id.bt_quanxuan);
lv = (ListView) findViewById(R.id.lv);
tv_num = (TextView) findViewById(R.id.tv_num);
tv_zongjai = (TextView) findViewById(R.id.tv_zongjai);
//获得数据
huodeshuju();
//设置监听
bt_fanxuan.setOnClickListener(this);
bt_quanxuan.setOnClickListener(this);
}
//------------------------------------
//获得网络数据
private void huodeshuju() {
new Thread(){
public void run() {
try {
URL url=new URL(urlPath);
HttpURLConnection urlConnection=(HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
int code=urlConnection.getResponseCode();
if (code==200) {
InputStream inputStream=urlConnection.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
String liner;
StringBuffer buffer=new StringBuffer();
while ((liner=reader.readLine())!=null) {
buffer.append(liner);
}
String str=buffer.toString();
Log.i("shuju:", str);
Message message=new Message();
message.what=0;
message.obj=str;
handler.sendMessage(message);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
@Override
public void onCheck(HashMap<Integer, Boolean> map) {
// TODO 自动生成的方法存根
total = 0.00f;
checkNum = 0;
for (int i = 0; i < map.size(); i++) {
if (map.get(i)) {
total += Float.valueOf(news.get(i).getMoney());
checkNum++;
}
}
//更新显示数据
dataChanged(total);
}
private void dataChanged(float total2) {
DecimalFormat decimalFormat = new DecimalFormat();// 构造方法的字符格式这里如果小数不足2位,会以0补足.
String price_num = decimalFormat.format(total);// format 返回的是字符串
String str = "合计" + "¥" + price_num + " ";
// 通知listView刷新
adapter.notifyDataSetChanged();
// 用TextView显示 总价、选中数量
tv_zongjai.setText(str);
tv_num.setText("已选中:"+checkNum);
}
//----------监听-----------------------
@Override
public void onClick(View v) {
switch (v.getId()) {
//全选
case R.id.bt_quanxuan:
//去SharedPreferences中获得是否为全选状态,true为全选状态,false为不是全选状态
boolean kk=sp.getBoolean("kk", false);
//为全选时,遍历设置为全不选
if (kk) {
// 遍历list的长度,设为未选
for (int i = 0; i < news.size(); i++) {
adapter.getIsSelected().put(i, false);
checkNum=0;// 数量减1
total = 0.00f;
}
// 刷新listview和TextView的显示
dataChanged(total);
//保存状态为全不选
Editor editor=sp.edit();
editor.putBoolean("kk", false);
editor.commit();
}else{
// 当不是全选时,设置为全选
total = 0.00f;
// 遍历list的长度,设为已选
checkNum = news.size();
for (int i = 0; i < news.size(); i++) {
adapter.getIsSelected().put(i, true);
total += Float.valueOf(news.get(i).getMoney()) ;
}
// 刷新listview和TextView的显示
dataChanged(total);
//保存全选状态
Editor editor=sp.edit();
editor.putBoolean("kk", true);
editor.commit();
}
break;
//反选
case R.id.bt_fanxuan:
checkNum=0;
//获得全选状态
boolean kkk=sp.getBoolean("kk", false);
total=0;
//为全选时,设置为全不选
if (kkk) {
// 遍历list的长度,设为未选
for (int i = 0; i < news.size(); i++) {
adapter.getIsSelected().put(i, false);
checkNum=0;// 数量减1
total = 0.00f;
}
// 刷新listview和TextView的显示
dataChanged(total);
Editor editor=sp.edit();
editor.putBoolean("kk", false);
editor.commit();
}else{
//不为全选时,也就是有选中的,有没选中的
// 遍历list的长度,设为未选
for (int i = 0; i < news.size(); i++) {
//获得当条目的选中状态
Boolean n=adapter.getIsSelected().get(i);
//如果选中,设为不选中
if (n) {
adapter.getIsSelected().put(i, false);
//获得选中条目的布尔值
Boolean a=adapter.getIsSelected().get(i);
//
if (a) {
total+=Float.valueOf(news.get(i).getMoney());
Log.i("总价111:", total+"");
checkNum++;// 数量减1
}
}else{
adapter.getIsSelected().put(i, true);
Boolean a=adapter.getIsSelected().get(i);
if (a) {
total+=Float.valueOf(news.get(i).getMoney());
Log.i("总价222:", total+"");
checkNum++;// 数量减1
}
}
}
// 刷新listview和TextView的显示
dataChanged(total);
}
break;
default:
break;
}
}
}
//==============以上是MainActivity==================完了,赶快试试吧============
Android中购物车的全选、反选、问题和计算价格的更多相关文章
- 关于Winform下DataGridView中实现checkbox全选反选、同步列表项的处理
近期接手一个winform 项目,虽然之前有.net 的经验,但是对一些控件的用法还不是很熟悉. 这段时间将会记录一些在工作中遇到的坎坷以及对应的解决办法,写出来与大家分享并希望大神提出更好解决方法来 ...
- C# WinForm中实现CheckBox全选反选功能
今天一群里有人问到这个功能,其实应该挺简单,但提问题的人问题的出发点并没有描述清楚.因此,一个简简单单的需求,就引起了群内热烈的讨论.下面看看这个功能如何去实现,先上效果: 下面直接上代码,请不要在意 ...
- web中的简单全选反选
<html> <body> <table> <tr> <th><input type="checkbox" onc ...
- bootstrap 中的 iCheck 全选反选功能的实现
喜欢bootstrap 风格的同学应该知道,iCheck的样式还是很好看的. 官网: http://www.bootcss.com/p/icheck/ 进入正题,iCheck提供了一些方法,可以进行全 ...
- Android开发 ---基本UI组件5:监听下拉选项,动态绑定下拉选项、全选/反选,取多选按钮的值,长按事件,长按删除,适配器的使用,提示查询数据,activity控制多按钮
效果图: 效果描述: 1.当点击 1 按钮后,进入选择城市的页面,会监听到你选中的城市名称:动态为Spinner绑定数据 2.当点击 2 按钮后,进入自动查询数据页面,只要输入首字母,就会动态查找以该 ...
- vue中的checkbox全选和反选
前几天有个博客园的朋友问小颖,小颖之前写的vue2.0在table中实现全选和反选 .Vue.js实现checkbox的全选和反选,为什么他将里面的js复制下来,但是实现不了全选和反选.小颖当时看他 ...
- vue+vant实现购物车的全选和反选业务,带你研究购物车的那些细节!
前言 喜欢购物的小伙伴看过来,你们期待已久的购物车来啦!相信小伙伴逛淘宝时最擅长的就是加入购物车了,那购物车是如何实现商品全选反选的呢?今天就带你们研究购物车的源码,以vue+vant为例. 正文 首 ...
- React中的全选反选问题
全选反选问题 1.在state里维护一个数组,例如showArr:[] 2.绑定点击事件的时候将当前这个当选按钮的index加进来 <span className='arrow' onClick ...
- html中全选反选
<!--第一层--> <div class="first"> <div class="first_top"> <img ...
随机推荐
- 对于querystring取值时候发生+号变空格的问题
今天遇到这个问题,在网上找了几个答案,解决了问题,很高兴,所以贴出来给大家分享一下: URL如下 http://127.0.0.1/test/test.aspx?sql= and id='300+' ...
- bootstrap-modal.js 居中问题
上下居中 引用 bootstrap-modalmanager.js 左右居中 修改 bootstrap-modal.js 中 this.$element.css('margin-left', '' ...
- SqlParameter关于Like的传参数无效问题
正确的写法(简洁版) private void GetHandleData(string strKeyWord1, string strKeyWord2, string strKeyWord3) { ...
- ubuntu下安装UltraEdit
在windows下常年使用UltraEdit来查看log,现在突然切换到ubuntu下,系统自带的Text Editor相当不适应:只有自己安装了. 首先,需要下载安装包,可以去:http://www ...
- 【python问题系列--2】脚本运行出现语法错误:IndentationError: unindent does not match any outer indentation level
缩进错误,此错误,最常见的原因是行之间没有对齐. 参考:http://www.crifan.com/python_syntax_error_indentationerror/comment-page- ...
- Android.mk简单分析
LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE_TAGS := optional LOCAL_SRC_FILES := $ ...
- 转:Jmeter之使用CSV Data Set Config实现参数化登录
在使用Jemeter做压力测试的时候,往往需要参数化用户名,密码以到达到多用户使用不同的用户名密码登录的目的.这个时候我们就可以使用CSV Data Set Config实现参数化登录: 首先通过Te ...
- log4net 日志文件占用,不能及时释放
在appender 下面加 <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
- sql语句--查询语句(MySQL)
1.截取字符串 left(str, length),right(str, length),substring(str, pos, length) 原文:http://www.jb51.net/arti ...
- hdu_1969_pie(二分)
题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1969 题意:看了老半天,就是有N个饼,要分给f+1个人,每个人只能一样多,不能拼凑,多余的丢弃,问每个 ...