在项目中经常需要选择手机系统里面的图片,但是直接启动系统页面,只能选择单张图片,而且UI不受我们自己控制,不灵活,所以这里仿照微信的大致效果,做一个图片选择器
加载图片的时候,使用的开源项目Universal-Image-Loader,示例代码如下:
MyApplication类:
package com.home.imgscan; import android.app.Application; import android.content.Context; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); initImageLoader(this,false); } /** * 初始化ImageLoader(在Application的onCreate()中调用) * * @param context * 上下文对象 * @param isDebug * 是否启用Debug模式 */ public static void initImageLoader(Context context, boolean isDebug) { // 创建默认的ImageLoader配置参数 ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder( context); if (isDebug) { builder.writeDebugLogs(); } ImageLoaderConfiguration configuration = builder.build(); ImageLoader.getInstance().init(configuration); } }主页面:MainActivity:
package com.home.imgscan; import java.util.ArrayList; import java.util.List; import android.annotation.SuppressLint; import android.app.Activity; import android.app.ProgressDialog; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.GridView; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener { // GridView控件 private GridView gridView; // 进度对话框 private ProgressDialog mProgressDialog; // 本地图片路径集合 private List<String> list = new ArrayList<String>(); // 加载完成标示 private final static int SCAN_OK = 1; // 适配器 private ScanAdapter adapter; // 发送按钮 private TextView sendView; @SuppressLint("HandlerLeak") private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case SCAN_OK: mProgressDialog.dismiss(); setAdapter(); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); initView(); getImages(); } /** * 初始化页面控件 */ private void initView() { gridView = (GridView) findViewById(R.id.main_grid); // 发送按钮 sendView = (TextView) findViewById(R.id.main_btn_send); sendView.setOnClickListener(this); } /** * 设置适配器 */ private void setAdapter() { if (adapter == null) { adapter = new ScanAdapter(MainActivity.this, list); gridView.setAdapter(adapter); } else { adapter.setList(list); adapter.notifyDataSetChanged(); } } /** * 获取手机上的图片 */ private void getImages() { if (!Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { Toast.makeText(this, "SD卡不存在", Toast.LENGTH_SHORT).show(); return; } mProgressDialog = ProgressDialog.show(this, null, "正在加载请稍后..."); new Thread(new Runnable() { @Override public void run() { Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; ContentResolver mContentResolver = MainActivity.this .getContentResolver(); Cursor mCursor = mContentResolver.query(mImageUri, null, MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?", new String[] { "image/jpeg", "image/png" }, MediaStore.Images.Media.DATE_MODIFIED); while (mCursor.moveToNext()) { String path = mCursor.getString(mCursor .getColumnIndex(MediaStore.Images.Media.DATA)); list.add(path); } mCursor.close(); mHandler.sendEmptyMessage(SCAN_OK); } }).start(); } /** * 更新发送按钮 */ public void updateSendBtn() { List<String> hasCheckedList = adapter.getHasCheckList(); if (hasCheckedList == null || hasCheckedList.size() == 0) { sendView.setText("发送"); } else { int size = hasCheckedList.size(); sendView.setText("发送(" + size + "/9)"); } } @Override public void onClick(View v) { if (v.getId() == R.id.main_btn_send) { List<String> hasCheckedList = adapter.getHasCheckList(); if (hasCheckedList == null || hasCheckedList.size() == 0) { Toast.makeText(this, "请选择图片", Toast.LENGTH_SHORT).show(); return; } // 发送。。。 } } }自定义适配器ScanAdapter:
package com.home.imgscan; import java.util.ArrayList; import java.util.List; import android.graphics.Bitmap; import android.text.TextUtils; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.Toast; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.download.ImageDownloader.Scheme; public class ScanAdapter extends BaseAdapter { private List<String> list; private LayoutInflater inflater; // 已经选择的图片本地路径集合 private List<String> hasCheckList = new ArrayList<String>(); private MainActivity activity; public ScanAdapter(MainActivity activity, List<String> list) { this.list = list; this.activity = activity; inflater = LayoutInflater.from(activity); } @Override public int getCount() { return list == null ? 0 : list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup arg2) { if (convertView == null) { convertView = inflater.inflate(R.layout.grid_content, null); } String path = list.get(position); // 选择框 ImageView box = getAdapterView(convertView, R.id.grid_content_box, path); box.setOnClickListener(new MyOnClickListener()); // 图片控件 ImageView iv = getAdapterView(convertView, R.id.grid_content_iv, path); setLocalImg(iv, path); return convertView; } private class MyOnClickListener implements OnClickListener { @Override public void onClick(View v) { if (v.getId() != R.id.grid_content_box) { return; } String path = (String) v.getTag(); if (TextUtils.isEmpty(path)) { return; } if (hasCheckList.contains(path)) { hasCheckList.remove(path); v.setBackgroundResource(R.drawable.box_unchecked); } else { if (hasCheckList.size() >= 9) { Toast.makeText(activity, "最多只能选择9张图片", Toast.LENGTH_SHORT) .show(); return; } hasCheckList.add(path); v.setBackgroundResource(R.drawable.box_checked); } activity.updateSendBtn(); } } @SuppressWarnings("unchecked") public <T extends View> T getAdapterView(View convertView, int id, Object tag) { SparseArray<View> viewHolder = null; try { if (convertView.getTag(R.id.view_holder) instanceof SparseArray<?>) { viewHolder = (SparseArray<View>) convertView .getTag(R.id.view_holder); } } catch (ClassCastException e) { } if (viewHolder == null) { viewHolder = new SparseArray<View>(); convertView.setTag(R.id.view_holder, viewHolder); convertView.setTag(R.id.path, tag); } View childView = viewHolder.get(id); if (childView == null) { childView = convertView.findViewById(id); childView.setTag(tag); viewHolder.put(id, childView); } return (T) childView; } /** * 加载本地图片 * * @param imageView * 图片ImageView控件 * @param imagePath * 图片本地路径 */ public static void setLocalImg(ImageView imageView, String imagePath) { // 显示图片的配置 DisplayImageOptions.Builder builder = new DisplayImageOptions.Builder(); builder.cacheInMemory(true).cacheOnDisk(true) .bitmapConfig(Bitmap.Config.RGB_565); DisplayImageOptions options = builder.build(); ImageLoader.getInstance().displayImage(Scheme.FILE.wrap(imagePath), imageView, options); } public List<String> getList() { return list; } public void setList(List<String> list) { this.list = list; } public List<String> getHasCheckList() { return hasCheckList; } public void setHasCheckList(List<String> hasCheckList) { this.hasCheckList = hasCheckList; } }
布局文件main.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="match_parent" android:background="@android:color/white" android:orientation="vertical" > <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/background_dark" > <ImageView android:id="@+id/main_iv_back" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_margin="10dp" android:background="@drawable/back" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="图片" android:textColor="@android:color/white" android:textSize="20sp" /> <TextView android:id="@+id/main_btn_send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginTop="10dp" android:background="@android:color/holo_green_light" android:padding="10dp" android:text="发送" android:textColor="@android:color/white" android:textSize="18sp" /> </RelativeLayout> <GridView android:id="@+id/main_grid" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/white" android:cacheColorHint="@android:color/transparent" android:gravity="center" android:horizontalSpacing="1dp" android:listSelector="@android:color/transparent" android:numColumns="3" android:scrollbars="none" android:stretchMode="columnWidth" android:verticalSpacing="1dp" > </GridView> </LinearLayout>
布局文件grid_content.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="wrap_content" android:background="@android:color/black" > <ImageView android:id="@+id/grid_content_iv" android:layout_width="match_parent" android:layout_height="100dp" android:scaleType="centerCrop" /> <ImageView android:id="@+id/grid_content_box" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="6dp" android:layout_marginTop="6dp" android:background="@drawable/box_unchecked" /> </RelativeLayout>示例下载链接:http://download.csdn.net/detail/u010142437/8854871
版权声明:本文为博主原创文章,未经博主允许不得转载。