网上编辑购物车全选,取消全选的例子有很多,我最近正好在做这个功能,然后就整理了好多网上的例子,把好几个人的思想整理到我的项目中,东西虽然不多,但也费不少劲。。今天终于测试好了。上图看看效果吧~~
第一张:选择单个商品
全选。
全不选我就不上图了
现在开始代码吧:
第一个布局文件 activity_act_view.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" > <RelativeLayout android:id="@+id/titlerelativelayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/title_background" android:gravity="center_vertical" > <LinearLayout android:id="@+id/ShoppingCart_top" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:gravity="center_vertical" android:orientation="vertical" android:padding="10dp" > <TextView android:id="@+id/ShoppingCart_title_txt" android:layout_width="68dp" android:layout_height="wrap_content" android:gravity="center_vertical" android:text="购物车" android:textColor="#FF8C00" android:textSize="17sp" /> </LinearLayout> <TextView android:id="@+id/Cart_toEdit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_marginLeft="10dp" android:layout_centerVertical="true" android:text="编辑" android:textColor="#4F4F4F" android:textSize="17sp" /> </RelativeLayout> <com.shop.eshopservice.xListView.XListView android:id="@+id/ShoppingCartListView" android:layout_width="match_parent" android:layout_height="match_parent" android:cacheColorHint="#00000000" android:fastScrollEnabled="true" android:layout_below="@+id/titlerelativelayout" /> <LinearLayout android:id="@+id/linear_cartOrderBottom" android:layout_width="match_parent" android:layout_height="50dp" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:background="@drawable/bottom_border" android:orientation="horizontal" > <CheckBox android:id="@+id/cb_cart_all" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:text="全选" android:textColor="#000000" /> <TextView android:id="@+id/cart_orderallmoney" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="right" android:layout_marginRight="10dp" android:text="合计:¥0.00" android:textColor="#FF0000" android:textSize="13sp" /> <TextView android:id="@+id/cart_pro_tobuy" android:layout_width="90dp" android:layout_height="50dp" android:background="#FF5000" android:layout_marginRight="10dp" android:gravity="center" android:text="结算" android:textColor="#ffffff" /> </LinearLayout> </RelativeLayout>
这里我用的是自定义的ListView。然后购物车的单个商品详情 item_shoppingcart.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="wrap_content" android:background="@drawable/list_background" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="right"> <TextView android:id="@+id/Cart_toEdit" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_marginRight="10dp" android:layout_marginTop="7dp" android:gravity="right" android:text="编辑" android:textColor="#4F4F4F" android:textSize="12sp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="5" android:layout_margin="8dp"> <CheckBox android:id="@+id/cb" android:layout_width="wrap_content" android:layout_height="wrap_content" android:focusable="false" android:gravity="center" android:layout_marginTop="19dp" android:focusableInTouchMode="false" android:clickable="false" android:checkMark="?android:attr/listChoiceIndicatorMultiple"/> <ImageView android:id="@+id/CartItemImage" android:layout_width="260dp" android:layout_height="70dp" android:layout_weight="8" android:background="@drawable/list_background_imgbg" android:padding="0dp" android:scaleType="centerInside" android:src="@drawable/shop_photo_frame" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="5" android:orientation="vertical" android:paddingRight="5dp" > <RelativeLayout android:id="@+id/ItemTopLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="37" android:paddingTop="7dp" > <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/cartItemTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:ellipsize="end" android:marqueeRepeatLimit="marquee_forever" android:paddingLeft="10dp" android:paddingRight="2dp" android:text="商品标题" android:textColor="#4F4F4F" android:textSize="12sp" /> </RelativeLayout> </RelativeLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="40" android:gravity="bottom" android:paddingBottom="9dp" android:paddingLeft="10dp" > <LinearLayout android:id="@+id/Itembottemleft" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_vertical" > <TextView android:id="@+id/CartItemPrice" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_marginRight="10dp" android:gravity="bottom" android:text="¥110" android:textColor="#f44415" android:textSize="11sp" /> </LinearLayout> <LinearLayout android:id="@+id/Itembottemright" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_alignParentRight="true" android:gravity="bottom" android:orientation="horizontal" android:paddingRight="2dp" > <TextView android:id="@+id/CartItemCount" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_marginRight="8dp" android:gravity="bottom" android:text="X1" android:textColor="#666666" android:textSize="11sp" /> </LinearLayout> </RelativeLayout> </LinearLayout> </LinearLayout> </LinearLayout>
然后就是我的购物车代码了,因为我的主页面用的是FragmentPagerAdapter+ViewPager,所以每个类都继承了Fragment
package com.shop.eshopservice; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.animation.AnimationSet; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageView; import android.widget.TextView; import com.shop.eshopservice.Data.Data; import com.shop.eshopservice.adapter.ShoppingCartAdapter.onCheckedChanged; import com.shop.eshopservice.model.Model; import com.shop.eshopservice.model.Product; import com.shop.eshopservice.model.ShoppingCart; import com.shop.eshopservice.sqlite.dao.EShopOpenHelper; import com.shop.eshopservice.tool.ToastUtils; import com.shop.eshopservice.utils.LoadImg; import com.shop.eshopservice.utils.LoadPictrue; import com.shop.eshopservice.xListView.XListView; import com.shop.eshopservice.xListView.XListView.IXListViewListener; /** * 购物车模块 * @author Administrator * */ public class ActionActivity extends Fragment implements OnTouchListener, IXListViewListener, OnClickListener,onCheckedChanged{ private View view; private List<ShoppingCart> cartList = new ArrayList<ShoppingCart>(); private ShoppingCartAdapter cartAdapter; private EShopOpenHelper eshop; // private PullToRefreshListView mListView; private XListView mListView; private TextView tv_money,tv_toEdit,to_DelBuy; private CheckBox selectAll; private int pageIndex = 0; private int pageSize = 10; private int visibleLastIndex = 0; //最后的可视项索引 private int visibleItemCount; // 当前窗口可见项总数 float fist_down_Y = 0; private AnimationSet animationSet; private boolean[] is_choice; private onCheckedChanged listener; @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ view = inflater.inflate(R.layout.activity_act_view, container, false); eshop = new EShopOpenHelper(getActivity().getApplicationContext()); // mListView = (PullToRefreshListView) view.findViewById(R.id.ShoppingCartListView); mListView = (XListView)view.findViewById(R.id.ShoppingCartListView); tv_toEdit = (TextView)view.findViewById(R.id.Cart_toEdit); //总编辑按钮 to_DelBuy = (TextView)view.findViewById(R.id.cart_pro_tobuy); selectAll = (CheckBox)view.findViewById(R.id.cb_cart_all); selectAll.setOnClickListener(this); is_choice=new boolean[cartList.size()]; // selectAll.set tv_money = (TextView)view.findViewById(R.id.cart_orderallmoney); cartList = eshop.selShoppingCart(pageIndex,pageSize); //从数据库获取购物车的数据 cartAdapter = new ShoppingCartAdapter(cartList, getActivity().getApplicationContext()); // mListView.setOnScrollListener(this); mListView.setOnTouchListener(this); mListView.setXListViewListener(this); // 设置可以进行下拉加载的功能 mListView.setPullLoadEnable(true); mListView.setPullRefreshEnable(true); // tv_money.setText(""); /*mListView.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { new GetDataTask(getActivity(), 0).execute(); } @Override public void onLoadMore() { new GetDataTask(getActivity(), 1).execute(); } });*/ selectAll.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton arg0, boolean arg1) { // 记录列表每一行的选中状态数量 int isChoice_all = 0; if(arg1){ Data.Allprice_cart = 0; // 设置全选 for(int i = 0;i < cartAdapter.getCount();i++){ cartAdapter.selectedMap.put(i, true); if(cartList.size()!=0){ //购物车里有商品 Data.Allprice_cart +=(cartList.get(i).getLocalprice())*cartList.get(i).getProcount(); } } tv_money.setText("合计:¥"+Data.Allprice_cart+""); //这里的Data.Allprice_cart是我单独定义的一个放静态数据的类 }else { // 设置全部取消 for (int i = 0; i < cartAdapter.getCount(); i++) { // 判断列表每一行是否处于选中状态,如果处于选中状态,则计数+1 if(cartAdapter.selectedMap.get(i)){ // 计算出列表选中状态的数量 isChoice_all += 1; } } // 判断列表选中数是否等于列表的总数,如果等于,那么就需要执行全部取消操作 if (isChoice_all == cartAdapter.getCount()) { // 如果没有选中了全选,那么就将列表的每一行都不选 for (int i = 0; i < cartAdapter.getCount(); i++) { // 列表每一行都取消 cartAdapter.selectedMap.put(i, false); if(cartList.size()!=0){ //购物车里有商品 Data.Allprice_cart -=(cartList.get(i).getLocalprice())*cartList.get(i).getProcount(); } } } tv_money.setText("合计:¥"+Data.Allprice_cart+""); cartAdapter.notifyDataSetChanged(); } } }); mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(id<0){ return; // 点击的是headerView或者footerView } Intent intent = new Intent(getActivity(), GoodsDetailActivity.class); Bundle bund = new Bundle(); ShoppingCart cart = (ShoppingCart) parent.getAdapter().getItem(position); bund.putSerializable("CartInfo",cart); intent.putExtra("cartvalue",bund); intent.putExtra("cart", "cart"); startActivity(intent); } }); cartAdapter.notifyDataSetChanged(); mListView.setAdapter(cartAdapter); return view; } /** * 滑动时被调用 */ /*@Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { this.visibleItemCount = visibleItemCount; visibleLastIndex = firstVisibleItem + visibleItemCount -1; } *//** * 当滑动改变时调用 *//* @Override public void onScrollStateChanged(AbsListView view, int scrollState) { int itemsLastIndex = cartAdapter.getCount() -1; //数据集最后一项的索引 int lastIndex = itemsLastIndex +1; if(scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastIndex){ //如果是自动加载,可以在这里放置异步加载数据的代码 Log.i("LOADMORE", "loading..."); } }*/ private class GetDataTask extends AsyncTask<Void, Void, List<Product>> { private Context context; private int index; public GetDataTask(Context context, int index) { this.context = context; this.index = index; } @Override protected List<Product> doInBackground(Void... arg0) { return null; } @Override protected void onPostExecute(List<Product> result) { if (index == 0) { pageIndex = 0; cartList = eshop.selShoppingCart(pageIndex,pageSize); // SimpleDateFormat format = new SimpleDateFormat( // "yyyy年MM月dd日 HH:mm"); // String date = format.format(new Date()); // mListView.onRefreshComplete(date); } else if (index == 1) { pageIndex += 10; cartList = eshop.selShoppingCart(pageIndex,pageSize); if(cartList.size() > 0){ for (int i = 0; i < cartList.size(); i++) { ShoppingCart cart = cartList.get(i); cartAdapter.addCartItem(cart); } }else{ ToastUtils.ToastMessage(getActivity().getApplicationContext(), "亲,已经是最后一条数据啦..."); } cartAdapter.notifyDataSetChanged(); // mListView.onLoadMoreComplete(); } onLoad(); super.onPostExecute(result); } } @Override public void onRefresh() { new GetDataTask(getActivity(), 0).execute(); } @Override public void onLoadMore() { new GetDataTask(getActivity(), 1).execute(); } @Override public boolean onTouch(View arg0, MotionEvent event) { float y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: //第一次按下时的坐标 fist_down_Y = y; break; case MotionEvent.ACTION_MOVE: if (fist_down_Y - y > 250) { if (animationSet != null) { animationSet = null; } // animationSet = (AnimationSet) AnimationUtils.loadAnimation(this, R.anim.up_out); } // 向下滑动,显示搜索栏 if (y - fist_down_Y > 250) { if (animationSet != null) { animationSet = null; } // animationSet = (AnimationSet) AnimationUtils.loadAnimation(this, R.anim.down_in); } break; } return false; } /** 停止加载和刷新 */ private void onLoad() { mListView.stopRefresh(); // 停止加载更多 mListView.stopLoadMore(); // 设置最后一次刷新时间 mListView.setRefreshTime(getCurrentTime(System.currentTimeMillis())); } /** 简单的时间格式 */ public static SimpleDateFormat mDateFormat = new SimpleDateFormat("MM-dd HH:mm"); public static String getCurrentTime(long time) { if (0 == time) { return ""; } return mDateFormat.format(new Date(time)); } @Override public void getChoiceData(int position, boolean isChoice) { if(isChoice){ if(cartList.size()!=0){ //购物车里有商品 Data.Allprice_cart +=(cartList.get(position).getLocalprice())*cartList.get(position).getProcount(); } }else{ if(cartList.size()!=0){ Data.Allprice_cart -=(cartList.get(position).getLocalprice())*cartList.get(position).getProcount(); } } // 记录列表处于选中状态的数量 int num_choice = 0; for (int i = 0; i < cartAdapter.getCount(); i++) { if(cartList !=null &&(cartAdapter.selectedMap.get(i))){ num_choice ++; } } if(num_choice == cartList.size()){ selectAll.setChecked(true); } else { selectAll.setChecked(false); } tv_money.setText("合计:¥"+Data.Allprice_cart+""); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.Cart_toEdit: tv_toEdit.setText("完成"); to_DelBuy.setText("删除"); break; case R.id.cb_cart_all: // if(selectAll.isChecked()){ // for(int i =0;i< cartAdapter.getCount();i++){ // cartAdapter.selectedMap.put(i, true); //// cartAdapter.delContactsIdSet.add(String.valueOf(cartAdapter.list.get(i).getId())); // } // // }else{ // for (int i = 0; i < cartAdapter.getCount(); i++) { // cartAdapter.selectedMap.put(i, false); //// cartAdapter.delContactsIdSet.clear(); // } // } cartAdapter.notifyDataSetChanged(); break; } } class ShoppingCartAdapter extends BaseAdapter { //保存listview item的状态 HashMap<Integer,View> map = new HashMap<Integer,View>(); List<ShoppingCart> list; // 用来控制CheckBox的选中状况 Map<Integer, Boolean> selectedMap; // HashSet<String> delContactsIdSet; Context ctx; private LoadImg loadImg; private double allMoney = 0.0; public ShoppingCartAdapter(List<ShoppingCart> list, Context ctx) { this.list = list; this.ctx = ctx; // delContactsIdSet = new HashSet<String>(); selectedMap = new HashMap<Integer, Boolean>(); initDate(); } // 初始化isSelected的数据 private void initDate() { for (int i = 0; i < list.size(); i++) { selectedMap.put(i,false); } } public void setList(List<ShoppingCart> proList){ this.list = proList; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int arg0) { return list.get(arg0); } @Override public long getItemId(int arg0) { return arg0; } public void addCartItem(ShoppingCart cart){ list.add(cart); } @Override public View getView(final int position, View convertView, ViewGroup parent) { Holder hold = null; View view = null; if(map.get(position) == null){ // 获得ViewHolder对象 // 导入布局并赋值给convertview LayoutInflater mInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = mInflater.inflate(R.layout.item_shoppingcart, null); hold = new Holder(); hold.toEdit = (TextView)view.findViewById(R.id.Cart_toEdit); hold.mTitle = (TextView) view.findViewById(R.id.cartItemTextView); //产品标题 hold.mImage = (ImageView) view.findViewById(R.id.CartItemImage); //产品图片 hold.mPrice = (TextView) view.findViewById(R.id.CartItemPrice); //产品价格 hold.mCount = (TextView) view.findViewById(R.id.CartItemCount); hold.check_goods = (CheckBox)view.findViewById(R.id.cb); final int p = position; hold.check_goods.setChecked(selectedMap.get(position)); hold.check_goods.setOnClickListener(new OnClickListener() { @Override public void onClick(View vi) { //selectedMap.put(p, true); } }); hold.check_goods.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton arg0, boolean isChoice) { if(isChoice){ selectedMap.put(p, true); }else{ selectedMap.put(p, false); } getChoiceData(position, isChoice); //当每次选中发生变化时调用它进行判断 } }); view.setTag(hold); }else{ //取出hold view = map.get(position); hold = (Holder)view.getTag(); } hold.mTitle.setText(ToDBC(list.get(position).getTitle())); hold.mImage.setTag(Model.SHOPLISTIMGURL + list.get(position).getImageUrl()); hold.mPrice.setText("¥"+list.get(position).getLocalprice() + ""); hold.mCount.setText("X"+list.get(position).getProcount()); // 设置默认显示的图片 hold.mImage.setImageResource(R.drawable.shop_photo_frame); LoadPictrue.loadImage4(hold.mImage.getTag().toString() ,hold.mImage); //缓存加载图片 return view; } //规定布局页面标题换行代码 public String ToDBC(String input) { char[] c = input.toCharArray(); for (int i = 0; i< c.length; i++) { if (c[i] == 12288) { c[i] = (char) 32; continue; }if (c[i]> 65280&& c[i]< 65375) c[i] = (char) (c[i] - 65248); } return new String(c); } class Holder { public TextView mTitle, mPrice, mCount,toEdit; public ImageView mImage; public CheckBox check_goods; } } }
我去,代码竟然这么长,看起来可能有点费劲,但功能实现就好。