網上編輯購物車全選,取消全選的例子有不少,我最近正好在作這個功能,而後就整理了好多網上的例子,把好幾我的的思想整理到個人項目中,東西雖然很少,但也費很多勁。。今天終於測試好了。上圖看看效果吧~~java
第一張:選擇單個商品android
全選。web
全不選我就不上圖了sql
如今開始代碼吧:數據庫
第一個佈局文件 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.xmlapp
<?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; } } }
我去,代碼居然這麼長,看起來可能有點費勁,但功能實現就好。ide