Android之附加图片2—— 从系统图库中选择图片

上一篇博客讲述了模仿微信图片选择器来附加图片,本篇就来讲述直接从系统图库中选择图片。具体功能如下:
(1)从手机图库中最多选择3张图片,每次只能选择一张;
(2)选择的图片可以点击移除然后再添加新图片;
本博客主要实现的是以上功能,其他诸如主界面布局、各种控件添加和提交功能等旨在说明问题,只做了简单处理,重点在图片选择添加部分。
截图如下:
Android之附加图片2—— 从系统图库中选择图片_第1张图片
Android之附加图片2—— 从系统图库中选择图片_第2张图片

在这里提供源码下载地址,有兴趣的读者可以下载观看(注:我使用的 Android Studio 1.4 , SdkVersion 为23 ,在小米note【Android 4.4 】上调试运行)。

项目源码下载地址
Android之从系统图库选择图片.zip

下面主要叙述附加图片部分:
(1)界面布局,主要是一个GridView :

<GridView
    android:id="@+id/gridview"
    android:layout_width="fill_parent"
    android:layout_height="200dp"

    android:horizontalSpacing="2dp"
    android:verticalSpacing="5dp"
    android:scrollbars="none"
    android:listSelector="#00000000"
    android:numColumns="3" >
GridView>

(2)使用一个Intent重定向到系统图库,然后传送一个整形常量到startActivityForResult()方法,Java代码如下:

    /**
     * 进入系统原生图库选择照片
     */
    private void selectClick(){
        Intent intent = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        if(allSelectedPicture.size()< 3){
            startActivityForResult(intent, REQUEST_PICK);
        }
    }

(3)获取选择的图片,只要点击选择了一张图片,onActivityResult()方法将会被调用。然后处理这个方法得到的数据,代码如下:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQUEST_PICK && resultCode == RESULT_OK && null != data) {

                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };

                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);

                if(!allSelectedPicture.contains(picturePath)){
                    allSelectedPicture.add(picturePath);
                }
                cursor.close();

                gridview.setAdapter(gridAdapter);
        }
    }

(4)图片的选择和呈现都是在一个GridView上实现的,它的适配器定义如下:

class GridAdapter extends BaseAdapter {

        public LayoutInflater layoutInflater = LayoutInflater.from(context);
        @Override
        public int getCount() {
            return allSelectedPicture.size()+ 1;
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

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

                holder.image = (ImageView) convertView.findViewById(R.id.child_iv);
                holder.btn = (Button) convertView.findViewById(R.id.child_delete);

                holder.image.setScaleType(ImageView.ScaleType.CENTER_CROP);
                convertView.setTag(holder);
            }
            else{
                holder = (ViewHolder) convertView.getTag();
            }

            if (position == allSelectedPicture.size()) {
                holder.image.setBackgroundResource(R.drawable.icon_addpic);
                holder.btn.setVisibility(View.GONE);

                holder.image.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        selectClick();
                    }
                });
                if (position == 3) {
                    holder.image.setVisibility(View.GONE);
                }
            } else {
                ImageLoader.getInstance().displayImage("file://" + allSelectedPicture.get(position),
                        holder.image);

                holder.btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //点击后移除图片
                        allSelectedPicture.remove(position);

                        //更新UI
                        gridview.setAdapter(gridAdapter);
                    }
                });

            }
            return convertView;
        }
    }

    /**
     * 自定义的一个类用来缓存convertview
     */
    public class ViewHolder {
        public ImageView image;
        public Button btn ;
    }

(5)在GridView中item的布局,childgrid_item.xml :


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="120dp"
    android:layout_height="120dp" >

    <ImageView
        android:id="@+id/child_iv"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:scaleType="centerCrop"
         />

    <Button
        android:id="@+id/child_delete"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignParentRight="true"
        android:layout_margin="4dp"
        android:background="@drawable/ic_delete" />

RelativeLayout>

主界面布局文件的完整代码(和上一篇仿微信图片选择器一样),activity_main.xml :


<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:background="#f7614d"
        android:paddingLeft="37px"
        android:layout_height="70dp">
        <TextView
            android:layout_centerInParent="true"
            android:text="附加图片"
            android:textSize="25sp"
            android:textColor="#ffffff"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
    RelativeLayout>

    <View
        android:layout_width="fill_parent"
        android:layout_height="20dp"
        android:background="#00000000"/>

    <LinearLayout
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv11"
            android:layout_alignParentLeft="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="文字描述"
            android:textSize="23sp"
            />
        <View
            android:layout_width="fill_parent"
            android:layout_height="10dp"
            android:background="#00000000"/>

        <EditText
            android:paddingTop="20dp"
            android:background="@drawable/bg_et"
            android:id="@+id/editText"
            android:inputType="textMultiLine"
            android:gravity="left|top"
            android:padding="5dp"
            android:maxLength="300"
            android:hint="客官,写点评论吧..."
            android:textColorHint="#808080"
            android:textSize="20sp"
            android:layout_width="fill_parent"
            android:layout_height="150dp" />

        <View
            android:layout_width="fill_parent"
            android:layout_height="20dp"
            android:background="#00000000"/>
        <TextView
            android:id="@+id/tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="附加图片"
            android:textSize="23sp" />
        <View
            android:layout_width="fill_parent"
            android:layout_height="10dp"
            android:background="#00000000"/>

        <GridView
            android:id="@+id/gridview"
            android:layout_width="fill_parent"
            android:layout_height="200dp"

            android:horizontalSpacing="2dp"
            android:verticalSpacing="5dp"
            android:scrollbars="none"
            android:listSelector="#00000000"
            android:numColumns="3" >
        GridView>

        <Button
            android:id="@+id/submit_btn"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_centerInParent="true"
            android:background="@drawable/bg_submit"
            android:text="提交"
            android:textSize="23sp"
            android:textColor="#FFFFFF"/>
    LinearLayout>

LinearLayout>

完整的MainActivity.java文件如下:

package com.pictureselect;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

import java.util.ArrayList;

public class MainActivity extends Activity {
    public EditText editText ;

    public Button submit_btn ;

    public Context context;

    private static final int REQUEST_PICK = 0;

    private GridView gridview;

    private GridAdapter gridAdapter;

    //存放所有选择的照片
    private ArrayList allSelectedPicture = new ArrayList();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //设置在activity启动的时候输入法默认是不开启的
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        context = this ;

       ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                .threadPriority(Thread.NORM_PRIORITY - 2)//设置当前线程的优先级
                .denyCacheImageMultipleSizesInMemory()
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())//使用MD5对UIL进行加密命名
                .diskCacheSize(100 * 1024 * 1024)//50 Mb sd卡(本地)缓存的最大值
                .diskCacheFileCount(300)// 可以缓存的文件数量
                .tasksProcessingOrder(QueueProcessingType.LIFO)//后进先出
                .build();

        //初始化操作
        ImageLoader.getInstance().init(config);

        initView();
    }
    /**
     * 初始化视图
     */
    private void initView(){

         /* 其他控件省略*/

        //显示图片
        gridview = (GridView) findViewById(R.id.gridview);
        gridAdapter = new GridAdapter();
        gridview.setAdapter(gridAdapter);
    }

    /**
     * 进入系统原生图库选择照片
     */
    private void selectClick(){
        Intent intent = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        if(allSelectedPicture.size()< 3){
            startActivityForResult(intent, REQUEST_PICK);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQUEST_PICK && resultCode == RESULT_OK && null != data) {

                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };

                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);

                if(!allSelectedPicture.contains(picturePath)){
                    allSelectedPicture.add(picturePath);
                }
                cursor.close();
                gridview.setAdapter(gridAdapter);
        }
    }

    /**
     * 展示图片的GridView的适配器
     */
    class GridAdapter extends BaseAdapter {

        public LayoutInflater layoutInflater = LayoutInflater.from(context);
        @Override
        public int getCount() {
            return allSelectedPicture.size()+ 1;
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

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

                holder.image = (ImageView) convertView.findViewById(R.id.child_iv);
                holder.btn = (Button) convertView.findViewById(R.id.child_delete);

                holder.image.setScaleType(ImageView.ScaleType.CENTER_CROP);
                convertView.setTag(holder);
            }
            else{
                holder = (ViewHolder) convertView.getTag();
            }

            if (position == allSelectedPicture.size()) {
                holder.image.setBackgroundResource(R.drawable.icon_addpic);
                holder.btn.setVisibility(View.GONE);

                holder.image.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        selectClick();
                    }
                });
                if (position == 3) {
                    holder.image.setVisibility(View.GONE);
                }
            } else {
                ImageLoader.getInstance().displayImage("file://" + allSelectedPicture.get(position),
                        holder.image);

                holder.btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //点击后移除图片
                        allSelectedPicture.remove(position);

                        //更新UI
                        gridview.setAdapter(gridAdapter);
                    }
                });

            }
            return convertView;
        }
    }

    /**
     * 自定义的一个类用来缓存convertview
     */
    public class ViewHolder {
        public ImageView image;
        public Button btn ;
    }
}

项目源码下载地址
Android之从系统图库选择图片.zip

你可能感兴趣的:(java,移动开发,javascript)