GridView和CheckBox结合使用

源码下载地址:http://download.csdn.net/detail/chenming1990118/6402591

说明:1.调用系统相册,获得相册图片用gridview显示

            2.在checkbox事件中,先实例一个HashMap对象,当选中时,则把该图片的position和图片路径用HashMap存储,如:map.put(position,path)

               在全局变量声明一个 private ArrayList<HashMap<Integer, String>> tempList = new ArrayList<HashMap<Integer, String>>();

               再把map对象添加到ArrayList数组里面去,如:tempList.add(map);

            3.当取消时,则对所有已添加的ArrayList数组遍历,不能直接在循环中remove,否则会报ConcurrentModificationException异常,可用Iterator 迭代,在for循环                把HashMap 对象所有的key取出,用Set集合接收,再对Set集合遍历,判断postion是否与map的key相等,如果相等,则remove()


         Activity代码:

         

package com.test.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;

import com.test.adapter.GridViewApdapter;
import com.test.util.CacheMap;
import com.test.util.CameraAndPhotoLibUtil;

/**
 * 选择多张图片实现类
 * 
 * @author admin
 * 
 */
public class BatchUploadImgActivity extends Activity {

	private GridView gridView;

	private Button finishBt;

	private ArrayList<HashMap<String, String>> potos = new ArrayList<HashMap<String, String>>();

	private ArrayList<HashMap<Integer, String>> img_list;

	private GridViewApdapter gApdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.poto_gridview);

		initView();

		// 获取手机相册图片
		getSysPoto();

		initListener();
	}

	/**
	 * 界面初始化
	 */
	private void initView() {

		gridView = (GridView) findViewById(R.id.img_gridview);

		finishBt = (Button) findViewById(R.id.treasure_finish_button);
	}

	/**
	 * 事件初始化
	 */
	private void initListener() {

		finishBt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				//声明一个临时列表存储图片路径 
				ArrayList<String> temp_imgs = new ArrayList<String>();
				
				// 获得选择的图片路径 列表
				img_list = CacheMap.getDate();
				
				//对图片路径列表遍历且储存到临时列表
				for(HashMap<Integer, String> map : img_list) {
					Iterator<Entry<Integer, String>> iter = map.entrySet().iterator();
					while (iter.hasNext()) {
						Map.Entry<Integer, String> entry = (Entry<Integer, String>)iter.next();
						temp_imgs.add(entry.getValue());
					}
				}
				
				Log.i("temp_imgs size", temp_imgs.size() + "");
				
				Toast.makeText(getApplication(), "选择了" + temp_imgs.size() + "张图片", Toast.LENGTH_LONG).show();

				/*Intent intent = new Intent();

				intent.putExtra("img_list", temp_imgs);

				setResult(RESULT_OK, intent);

				finish();*/
			}
		});
	}

	/**
	 * 获取手机相册图片
	 */
	private void getSysPoto() {
		/*
		 * Log.i("come in", "come in"); Intent intentPhoto =
		 * CameraAndPhotoLibUtil.getPhoto( BatchUploadImgActivity.this,
		 * Intent.ACTION_GET_CONTENT, true); startActivityForResult(intentPhoto,
		 * REQUEST_PHOTOLIB);
		 */

		Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		String[] projection = { MediaStore.Images.Media._ID,
				MediaStore.Images.Media.DISPLAY_NAME,
				MediaStore.Images.Media.DATA, MediaStore.Images.Media.SIZE };
		String selection = MediaStore.Images.Media.MIME_TYPE + "=?";
		String[] selectionArg = { "image/jpeg" };
		Cursor mCursor = managedQuery(uri, projection, selection, selectionArg,
				MediaStore.Images.Media.DISPLAY_NAME);
		potos = CameraAndPhotoLibUtil.getSystemPotos(getApplication(), mCursor);
		Log.i("potos size", potos.size() + "");

		gApdapter = new GridViewApdapter(BatchUploadImgActivity.this, potos);
		gridView.setAdapter(gApdapter);
	}

	/*
	 * protected void onActivityResult(int requestCode, int resultCode, Intent
	 * data) {
	 * 
	 * if (resultCode != RESULT_OK) { Log.e("error",
	 * "ActivityResult resultCode error"); return; } switch (requestCode) { case
	 * REQUEST_CAMERA:// 拍照 Uri imageUri = data.getData(); Intent intentCut =
	 * CameraAndPhotoLibUtil.cropImageUri(imageUri, 60, 60);
	 * startActivityForResult(intentCut, REQUEST_CUT); break; case
	 * REQUEST_PHOTOLIB:// 相册 Log.i("come in poto", "come in poto"); Uri uri =
	 * data.getData();
	 * 
	 * ContentResolver resolver = getContentResolver();
	 * 
	 * String[] proj = { MediaStore.Images.Media.DATA };
	 * 
	 * Cursor cursor = managedQuery(uri, proj, null, null, null);
	 * 
	 * potos = CameraAndPhotoLibUtil.getSystemPotos(uri, getApplication(),
	 * cursor);
	 * 
	 * if(potos == null) { Log.e("error", "error"); }else { Log.i("poto size",
	 * potos.size() + ""); }
	 * 
	 * Bitmap bmPhoto = null; try { bmPhoto =
	 * MediaStore.Images.Media.getBitmap(resolver, uri);
	 * 
	 * String[] proj = { MediaStore.Images.Media.DATA };
	 * 
	 * Cursor cursor = managedQuery(uri, proj, null, null, null);
	 * 
	 * 
	 * if(cursor != null) { cursor.moveToFirst(); while(cursor.getPosition() !=
	 * cursor.getCount()) {
	 * 
	 * HashMap<String, String> maps = new HashMap<String, String>();
	 * 
	 * Log.i("column index",
	 * cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
	 * Log.i("column name",
	 * cursor.getString(cursor.getColumnIndex(MediaStore.Images
	 * .Media.DISPLAY_NAME)));
	 * 
	 * maps.put("imageId",
	 * cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
	 * maps.put("imageName",
	 * cursor.getString(cursor.getColumnIndex(MediaStore.Images
	 * .Media.DISPLAY_NAME)));
	 * 
	 * } }
	 * 
	 * // 获得用户选择的图片的索引值 //int column_index = cursor //
	 * .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	 * 
	 * // 将光标移至开头 ,这个很重要,不小心很容易引起越界 //cursor.moveToFirst();
	 * 
	 * // 最后根据索引值获取图片路径 //path = cursor.getString(column_index);
	 * 
	 * // String imgpath = FileUtils.getSDPath() + File.separator + //
	 * "nanfangyoudao";
	 * 
	 * // Log.i("path=", path);
	 * 
	 * } catch (FileNotFoundException e) { // TODO Auto-generated catch block
	 * e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated
	 * catch block e.printStackTrace(); } // Bitmap bmPhoto = (Bitmap)
	 * data.getExtras().get("data"); //imageButton.setImageBitmap(bmPhoto);
	 * 
	 * break; case REQUEST_CUT:// 裁剪 Bitmap bmCut = (Bitmap)
	 * data.getExtras().get("data");
	 * 
	 * //imageButton.setImageBitmap(bmCut); break;
	 * 
	 * default: break; } };
	 */

}

       适配器代码:

       

package com.test.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import android.content.Context;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;

import com.test.activity.R;
import com.test.util.CacheMap;

/**
 * 相册适配器
 * 
 * @author admin
 * 
 */
public class GridViewApdapter extends BaseAdapter {

	private LayoutInflater lInflater;

	private Context context;

	private ArrayList<HashMap<String, String>> list;

	private ArrayList<HashMap<Integer, String>> tempList = new ArrayList<HashMap<Integer, String>>();

	public GridViewApdapter(Context context,
			ArrayList<HashMap<String, String>> list) {

		this.context = context;

		this.list = list;

		lInflater = LayoutInflater.from(context);

	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub

		return list.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return 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) {
		// TODO Auto-generated method stub

		ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = lInflater.inflate(R.layout.gridview_item, null);

			holder.imageView = (ImageView) convertView
					.findViewById(R.id.poto_ItemImage);
			holder.checkBox = (CheckBox) convertView
					.findViewById(R.id.poto_checkbox);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		Bitmap bm = MediaStore.Images.Thumbnails.getThumbnail(
				context.getContentResolver(),
				Long.parseLong((String) list.get(position).get("imageId")),
				Images.Thumbnails.MICRO_KIND, null);

		holder.imageView.setImageBitmap(bm);

		holder.checkBox
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						// TODO Auto-generated method stub

						//每次进来都实例化map
						HashMap<Integer, String> map = new HashMap<Integer, String>();

						if (isChecked) {

							// SD卡图片的地址
							String path = list.get(position).get("imagePath");

							map.put(position, path);

							//将 map对象添加到list
							tempList.add(map);

						} else {
							/**
							 * 注意:不能直接对tempList列表循环在循环里面remove会报ConcurrentModificationException异常
							 */
							for (Iterator<HashMap<Integer, String>> it = tempList
									.iterator(); it.hasNext();) {
								
								HashMap<Integer, String> haMap = it.next();
								
								//取出Map里面所有的key
								Set<Integer> set = haMap.keySet();
								
								//对map里面所有的key循环
								for(Integer integer : set) {
									//如果选择的postition与key相等,则移除 
									if(integer.equals(position)) {
										it.remove();
									}
								}
							}
						}
						
						Log.i("tempList size", tempList.size()+"");
						
						CacheMap.putDate(tempList);
						
						for(HashMap<Integer, String> tempMap : tempList) {
							Iterator<Entry<Integer, String>> iter = tempMap.entrySet().iterator();
							while(iter.hasNext()) {
								Map.Entry<Integer, String> entry = (Entry<Integer, String>)iter.next();
								Log.i("key=" + entry.getKey(), ",value=" + entry.getValue());
							}
						}
					}
				});

		return convertView;
	}

	class ViewHolder {
		ImageView imageView;
		CheckBox checkBox;

	}
}

效果图:


            

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值