android 仿微信图片选择器

Posted 踏雪羽翼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android 仿微信图片选择器相关的知识,希望对你有一定的参考价值。

1、要实现首先在build.gradle中添加下面依赖库

compile 'com.github.bumptech.glide:glide:3.5.2'

    compile 'com.android.support:recyclerview-v7:25.0.+'

2、需要添加下面三个权限

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
3、先实现图片选择的activity,这里只使用了recycleView实现图片的展示,但可以实现右滑删除图片和长按移动调换图片位置,即可以更换不同item位置。效果图如下:


首先先写adapter代码的实现,这里主要对position位置做了判断,0的时候我们显示默认需要选的的图片,其他选择选中的图片。

if (position==0)
            holder.image.setVisibility(View.GONE);
            holder.ivB.setVisibility(View.VISIBLE);
            holder.image.setBackgroundResource(R.drawable.ic_launcher);
        else 
            holder.ivB.setVisibility(View.GONE);
            holder.image.setVisibility(View.VISIBLE);
            Glide.with(mContext)
                    .load(mSelectPath.get(position))
                    .centerCrop()
                    .into(holder.image);
        
然后写一个图片的点击监听回调到activity中处理

private MyItemOnClickListener myItemOnClickListener;

    public interface MyItemOnClickListener 
        void onItemClickListener(View view, int position);
    

    public void myItemOnClickListener(MyItemOnClickListener myItemOnClickListener) 
        this.myItemOnClickListener = myItemOnClickListener;
    

完整实现代码

package com.example.apple.imageselect.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.apple.imageselect.R;

import java.util.ArrayList;

/**
 * Created by apple on 17/10/9.
 */

public class MyTestAdapter extends RecyclerView.Adapter<MyTestAdapter.MyViewHolder> 

    private ArrayList<String> mSelectPath;
    private Context mContext;
    private LayoutInflater inflater;

    private MyItemOnClickListener myItemOnClickListener;

    public interface MyItemOnClickListener 
        void onItemClickListener(View view, int position);
    

    public void myItemOnClickListener(MyItemOnClickListener myItemOnClickListener) 
        this.myItemOnClickListener = myItemOnClickListener;
    


    public MyTestAdapter(Context mContext, ArrayList<String> selectPath) 
        this.mContext = mContext;
        this.mSelectPath = selectPath;

        inflater = LayoutInflater.from(mContext);
    

    public void setData(ArrayList<String> mSelectPath) 
        this.mSelectPath = mSelectPath;

    

    @Override
    public int getItemCount() 
        int count  = 0;
        if (mSelectPath!=null && mSelectPath.size()>0)
            count = mSelectPath.size();
        
        return count;
    

    @Override
    public MyTestAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) 


       // MyViewHolder holder = new MyViewHolder(LayoutInflater.from(mContext).inflate(R.layout.adapter_my_text, parent, false));
        View view = inflater.inflate(R.layout.adapter_my_text, parent, false);
        MyViewHolder holder = new MyViewHolder(view);
        return holder;
    

    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) 


        if (position==0)
            holder.image.setVisibility(View.GONE);
            holder.ivB.setVisibility(View.VISIBLE);
            holder.image.setBackgroundResource(R.drawable.ic_launcher);
        else 
            holder.ivB.setVisibility(View.GONE);
            holder.image.setVisibility(View.VISIBLE);
            Glide.with(mContext)
                    .load(mSelectPath.get(position))
                    .centerCrop()
                    .into(holder.image);
        


        holder.tvText.setText(mSelectPath.get(position));

        holder.llImage.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                myItemOnClickListener.onItemClickListener(v, position);

            
        );
    


    class MyViewHolder extends RecyclerView.ViewHolder 

        ImageView image;
        LinearLayout llImage;
        TextView tvText;
        ImageView ivB;


        public MyViewHolder(View itemView) 
            super(itemView);

            image = (ImageView) itemView.findViewById(R.id.image);
            llImage = (LinearLayout) itemView.findViewById(R.id.ll_image);
            tvText = (TextView)itemView.findViewById(R.id.tv_text);
            ivB = (ImageView)itemView.findViewById(R.id.iv_b);
        
    


这里是一行显示五个,recycleView的设置是

mRecyclerView.setLayoutManager(new GridLayoutManager(this, 5));
        mRecyclerView.setAdapter(myTestAdapter);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
实现不同item可以切换位置和右滑删除图片效果,这里是使用itemTouchHelper,详细代码中有注释,

 //用于recycleView不同item中间的切换和右滑删除图片
        ItemTouchHelper.Callback mCallback = new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT, ItemTouchHelper.RIGHT) 
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) 
                int fromPosition = viewHolder.getAdapterPosition();//得到拖动ViewHolder的position
                int toPosition = target.getAdapterPosition();//得到目标ViewHolder的position
                if (fromPosition!=0 && toPosition!=0 && selectPath!=null) 
                    if (fromPosition < toPosition) 
                        //分别把中间所有的item的位置重新交换
                        for (int i = fromPosition; i < toPosition; i++) 
                            Collections.swap(selectPath, i, i + 1);
                        
                     else 
                        for (int i = fromPosition; i > toPosition; i--) 
                            Collections.swap(selectPath, i, i - 1);
                        
                    
                    isMove = true;
                    myTestAdapter.notifyItemMoved(fromPosition, toPosition);
                    //返回true表示执行拖动
                    Log.e(TAG, "onMove fromPosition=" + fromPosition + " toPosition=" + toPosition);
                
                return true;
            

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) 

                int position = viewHolder.getAdapterPosition();
                Log.e(TAG, "onSwiped position=" + position + " direction="+viewHolder.getPosition());
                // mData.remove(position);
                if (position==0) 
                    myTestAdapter.notifyDataSetChanged();
                else 
                    if (!isMove && selectPath!=null && selectPath.size()>0) 
                        selectPath.remove(position);
                    
                    myTestAdapter.notifyItemRemoved(position);
                
            

            @Override
            public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) 
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
                // 
                if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) 
                    //左右滑动时改变Item的透明度
                    final float alpha = 1 - Math.abs(dX) / (float) viewHolder.itemView.getWidth();
                    viewHolder.itemView.setAlpha(alpha);
                    viewHolder.itemView.setTranslationX(dX);
                
            

            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) 
                super.onSelectedChanged(viewHolder, actionState);
                //当选中Item时候会调用该方法,重写此方法可以实现选中时候的一些动画逻辑
                
            

            @Override
            public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) 
                int position = viewHolder.getPosition();
                
                super.clearView(recyclerView, viewHolder);
                //当动画已经结束的时候调用该方法,重写此方法可以实现恢复Item的初始状态
                if (isMove) 
                    isMove = false;
                    myTestAdapter.notifyDataSetChanged();
                
            
        ;

        itemTouchHelper = new ItemTouchHelper(mCallback);
        itemTouchHelper.attachToRecyclerView(mRecyclerView);
这里使用Intent跳转到图片选择的activity然后通过onActivityResult获取返回的图片

Intent intent = new Intent();
                    intent.setClass(MainActivity.this, ImageSelectActivity.class);
                    startActivityForResult(intent, 1);

    /**
     * 用于更新显示返回的图片
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && null != data) 
            selectPath = data.getStringArrayListExtra("selectPath");
            Log.e(TAG, "selectPath=" + selectPath.size());
            selectPath.add(0, selectPath.get(0));
            myTestAdapter.setData(selectPath);
            mRecyclerView.setAdapter(myTestAdapter);
            myTestAdapter.notifyDataSetChanged();
        
    
完整代码为
package com.example.apple.imageselect;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.View;


import com.example.apple.imageselect.adapter.MyTestAdapter;

import java.util.ArrayList;
import java.util.Collections;

public class MainActivity extends AppCompatActivity 

    private final String TAG = "MainActivity";

    private RecyclerView mRecyclerView;
    private ArrayList<String> selectPath = new ArrayList<>();
    private MyTestAdapter myTestAdapter;

    private ItemTouchHelper itemTouchHelper;
    private boolean isMove = false;


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

        initView();
        initData();
    

    private void initData() 
        for (int i = 0; i < 20; i++) 
            selectPath.add("/storage/emulated/0/DCIM/Camera/IMG_20171014_150621.jpg");
        

        myTestAdapter.setData(selectPath);
        mRecyclerView.setAdapter(myTestAdapter);
        myTestAdapter.notifyDataSetChanged();
    

    private void initView() 

        mRecyclerView = (RecyclerView) findViewById(R.id.recycleView);

        // LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        myTestAdapter = new MyTestAdapter(getApplication(), selectPath);

        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 5));
        mRecyclerView.setAdapter(myTestAdapter);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        myTestAdapter.myItemOnClickListener(new MyTestAdapter.MyItemOnClickListener() 
            @Override
            public void onItemClickListener(View view, int position) 
                if (position == 0) 
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, ImageSelectActivity.class);
                    startActivityForResult(intent, 1);
                 else 

                    Bitmap bitmap = BitmapFactory.decodeFile(selectPath.get(position));
                    Drawable drawable = new BitmapDrawable(bitmap);

                
            
        );

        //用于recycleView不同item中间的切换和右滑删除图片
        ItemTouchHelper.Callback mCallback = new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT, ItemTouchHelper.RIGHT) 
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) 
                int fromPosition = viewHolder.getAdapterPosition();//得到拖动ViewHolder的position
                int toPosition = target.getAdapterPosition();//得到目标ViewHolder的position
                if (fromPosition!=0 && toPosition!=0 && selectPath!=null) 
                    if (fromPosition < toPosition) 
                        //分别把中间所有的item的位置重新交换
                        for (int i = fromPosition; i < toPosition; i++) 
                            Collections.swap(selectPath, i, i + 1);
                        
                     else 
                        for (int i = fromPosition; i > toPosition; i--) 
                            Collections.swap(selectPath, i, i - 1);
                        
                    
                    isMove = true;
                    myTestAdapter.notifyItemMoved(fromPosition, toPosition);
                    //返回true表示执行拖动
                    Log.e(TAG, "onMove fromPosition=" + fromPosition + " toPosition=" + toPosition);
                
                return true;
            

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) 

                int position = viewHolder.getAdapterPosition();
                Log.e(TAG, "onSwiped position=" + position + " direction="+viewHolder.getPosition());
                // mData.remove(position);
                if (position==0) 
                    myTestAdapter.notifyDataSetChanged();
                else 
                    if (!isMove && selectPath!=null && selectPath.size()>0) 
                        selectPath.remove(position);
                    
                    myTestAdapter.notifyItemRemoved(position);
                
            

            @Override
            public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) 
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
                // Log.e("nsc", "onChildDraw actionState="+actionState + " dx="+dX + " dy ="+dY);
                if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) 
                    //左右滑动时改变Item的透明度
                    final float alpha = 1 - Math.abs(dX) / (float) viewHolder.itemView.getWidth();
                    viewHolder.itemView.setAlpha(alpha);
                    viewHolder.itemView.setTranslationX(dX);
                
            

            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) 
                super.onSelectedChanged(viewHolder, actionState);
                //当选中Item时候会调用该方法,重写此方法可以实现选中时候的一些动画逻辑
                Log.e("nsc", "onSelectedChanged");
            

            @Override
            public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) 
                int position = viewHolder.getPosition();
                Log.e("nsc", "clearView="+selectPath + " position="+position);
                super.clearView(recyclerView, viewHolder);
                //当动画已经结束的时候调用该方法,重写此方法可以实现恢复Item的初始状态
                if (isMove) 
                    isMove = false;
                    myTestAdapter.notifyDataSetChanged();
                
            
        ;

        itemTouchHelper = new ItemTouchHelper(mCallback);
        itemTouchHelper.attachToRecyclerView(mRecyclerView);

    


    /**
     * 用于更新显示返回的图片
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && null != data) 
            selectPath = data.getStringArrayListExtra("selectPath");
            Log.e(TAG, "selectPath=" + selectPath.size());
            selectPath.add(0, selectPath.get(0));
            myTestAdapter.setData(selectPath);
            mRecyclerView.setAdapter(myTestAdapter);
            myTestAdapter.notifyDataSetChanged();
        
    

4、图片选择功能的实现,首先看效果

这里获取手机图片使用LoaderManager加载手机图片显示,实现该接口后会有三个方法,我们在onCreateLoader中添加下面代码

  @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) 
        String columns[] = new String[]
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DATE_ADDED,
                MediaStore.Images.Thumbnails.DATA;

        CursorLoader cursorLoader = new CursorLoader(
                this,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                columns,
                null,
                null,
                null);
        return cursorLoader;
    
然后在onLoadFinished中获取图片资源,然后更新显示

 /**
     * 获取数据库图片数据
     * @param loader
     * @param cursor
     */
    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) 
        if (mAllPath != null && mAllPath.size() > 0) 
            mAllPath.clear();
        
        if (cursor.moveToNext()) 
            int thumbPathIndex = cursor.getColumnIndex(MediaStore.Images.Thumbnails.DATA);
            int timeIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATE_ADDED);
            int pathIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);

            do 
                ImageData imageData = new ImageData();
                String thumbPath = cursor.getString(thumbPathIndex);
                Long date = cursor.getLong(timeIndex);
                String filepath = cursor.getString(pathIndex);
                imageData.setPath(filepath);
                mAllPath.add(imageData);
             while (cursor.moveToNext());
        
        mImageSelectAdapter.setData(mAllPath);
        gvImageShow.setAdapter(mImageSelectAdapter);
        mImageSelectAdapter.notifyDataSetChanged();
    

最后记得添加在初始化的时候添加

getLoaderManager().initLoader(1, null, ImageSelectActivity.this);
关于点击选中图片和设置最多只能选多少张的功能实现代码如下
 //item click
    class OnItemClickListener implements AdapterView.OnItemClickListener 

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
            int selectSize = getSelect().size();

            if (selectSize < 9) //用于设置需要获取的图片数量
                if (mAllPath.get(position).isSelect()) 
                    mAllPath.get(position).setSelect(false);
                 else 
                    mAllPath.get(position).setSelect(true);
                
                tvSelectNumber.setText(getSelect().size() + "");
                mImageSelectAdapter.notifyDataSetChanged();

                if (getSelect().size() ==0)
                    btnOk.setEnabled(false);
                else 
                    btnOk.setEnabled(true);
                

             else //如果图片数量超过不再设置图片为选中,并且显示设置的最大文件数量

                if (mAllPath.get(position).isSelect())
                    mAllPath.get(position).setSelect(false);
                    tvSelectNumber.setText(getSelect().size()  + "");
                    mImageSelectAdapter.notifyDataSetChanged();
                else 
                    Toast.makeText(getApplication(), "最多只能选择9张", Toast.LENGTH_SHORT).show();
                

            
        
    
选择图片功能的完整代码

package com.example.apple.imageselect;

import android.app.Activity;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.apple.imageselect.adapter.ImageSelectAdapter;
import com.example.apple.imageselect.data.ImageData;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by apple on 17/10/9.
 */

public class ImageSelectActivity extends Activity implements LoaderManager.LoaderCallbacks<Cursor>, View.OnClickListener

    private final String TAG = "ImageSelectActivity";

    private Button btnCancel;
    private Button btnOk;
    private TextView tvSelectNumber;
    private GridView gvImageShow;
    private ImageSelectAdapter mImageSelectAdapter;
    private List<ImageData> mAllPath = new ArrayList<>();
    private ArrayList<String> mSelectPath = new ArrayList<>();

    private TextView tvPreview;

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

        initView();
        initData();
    

    private void initView() 

        btnCancel = (Button) findViewById(R.id.btn_cancel);
        btnCancel.setOnClickListener(this);
        btnOk = (Button) findViewById(R.id.btn_ok);
        btnOk.setOnClickListener(this);
        tvSelectNumber = (TextView) findViewById(R.id.tv_select_number);
        gvImageShow = (GridView) findViewById(R.id.gv_image_show);
        gvImageShow.setOnItemClickListener(new OnItemClickListener());

        mImageSelectAdapter = new ImageSelectAdapter(ImageSelectActivity.this, mAllPath);
        gvImageShow.setAdapter(mImageSelectAdapter);


        tvPreview = (TextView)findViewById(R.id.tv_preview);
        tvPreview.setOnClickListener(this);
    

    private void initData() 
        getLoaderManager().initLoader(1, null, ImageSelectActivity.this);

        //初始如果没有选中的图片,确定不能被点击
        if (getSelect()==null || getSelect().size() ==0)
            btnOk.setEnabled(false);
        else 
            btnOk.setEnabled(true);
        
    



    @Override
    public void onClick(View v) 
        switch (v.getId()) 

            case R.id.btn_cancel:
                finish();
                break;

            case R.id.btn_ok://返回数据给MainActivity
                Intent intent = new Intent();
                intent.putStringArrayListExtra("selectPath", mSelectPath);
                ImageSelectActivity.this.setResult(RESULT_OK, intent);
                finish();
                break;

            case R.id.tv_preview://跳转到ImageShowActivity
                if (getSelect()!=null && getSelect().size()>0) 
                    tvPreview.setEnabled(true);
                    Intent intentP = new Intent(ImageSelectActivity.this, ImageShowActivity.class);
                    intentP.putStringArrayListExtra("showImage", mSelectPath);
                    startActivityForResult(intentP,1);
                else 

                    tvPreview.setEnabled(false);

                
                break;
        
    

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) 
        String columns[] = new String[]
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DATE_ADDED,
                MediaStore.Images.Thumbnails.DATA;

        CursorLoader cursorLoader = new CursorLoader(
                this,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                columns,
                null,
                null,
                null);
        return cursorLoader;
    

    /**
     * 获取数据库图片数据
     * @param loader
     * @param cursor
     */
    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) 
        if (mAllPath != null && mAllPath.size() > 0) 
            mAllPath.clear();
        
        if (cursor.moveToNext()) 
            int thumbPathIndex = cursor.getColumnIndex(MediaStore.Images.Thumbnails.DATA);
            int timeIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATE_ADDED);
            int pathIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);

            do 
                ImageData imageData = new ImageData();
                String thumbPath = cursor.getString(thumbPathIndex);
                Long date = cursor.getLong(timeIndex);
                String filepath = cursor.getString(pathIndex);
                imageData.setPath(filepath);
                mAllPath.add(imageData);
             while (cursor.moveToNext());
        
        mImageSelectAdapter.setData(mAllPath);
        gvImageShow.setAdapter(mImageSelectAdapter);
        mImageSelectAdapter.notifyDataSetChanged();
    

    @Override
    public void onLoaderReset(Loader<Cursor> loader) 

    


    //item click
    class OnItemClickListener implements AdapterView.OnItemClickListener 

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
            int selectSize = getSelect().size();

            if (selectSize < 9) //用于设置需要获取的图片数量
                if (mAllPath.get(position).isSelect()) 
                    mAllPath.get(position).setSelect(false);
                 else 
                    mAllPath.get(position).setSelect(true);
                
                tvSelectNumber.setText(getSelect().size() + "");
                mImageSelectAdapter.notifyDataSetChanged();

                if (getSelect().size() ==0)
                    btnOk.setEnabled(false);
                else 
                    btnOk.setEnabled(true);
                

             else //如果图片数量超过不再设置图片为选中,并且显示设置的最大文件数量

                if (mAllPath.get(position).isSelect())
                    mAllPath.get(position).setSelect(false);
                    tvSelectNumber.setText(getSelect().size()  + "");
                    mImageSelectAdapter.notifyDataSetChanged();
                else 
                    Toast.makeText(getApplication(), "最多只能选择9张", Toast.LENGTH_SHORT).show();
                

            
        
    

    /**
     * 获取选中的图片
     * @return
     */
    private List<String> getSelect() 

        if (mSelectPath != null && mSelectPath.size() > 0) 
            mSelectPath.clear();
        
        if (mAllPath != null && mAllPath.size() > 0) 
            for (int i = 0; i < mAllPath.size(); i++) 
                if (mAllPath.get(i).isSelect()) 
                    mSelectPath.add(mAllPath.get(i).getPath());
                
            
        
        return mSelectPath;
    


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && null != data) 

            boolean isEdit = data.getBooleanExtra("isEdit",false);
            if (mSelectPath !=null && mSelectPath.size()>0)
                mSelectPath.clear();
            

            mSelectPath = data.getStringArrayListExtra("editFile");
            Log.e(TAG, "onActivityResult mSelectPath="+mSelectPath.size());
            if (isEdit)
                Intent intent = new Intent();
                intent.putStringArrayListExtra("selectPath", mSelectPath);
                ImageSelectActivity.this.setResult(RESULT_OK, intent);
                finish();
            

        
    
5、实现图片选中或跳转到编辑界面

实现该功能也不难,这里使用了洪洋写的ZoomImageView实现图片的放大缩小和左右滑动功能,滑动使用了viewPager,需要注意的是图片数量显示需要在setPrimaryItem中显示,否则上面显示的数字可能会显示不正确。

final ImageView[] mImageViews = new ImageView[mShowImageList.size()];

        viewPager.setAdapter(new PagerAdapter() 

            @Override
            public Object instantiateItem(ViewGroup container, int position) 
                ZoomImageView zoomImageView = new ZoomImageView(getApplication());
                File file = new File(mShowImageList.get(position));
                Glide.with(getApplication())
                        .load(file)
                        .into(zoomImageView);

                mImageViews[position] = zoomImageView;
                container.addView(zoomImageView);
                return zoomImageView;
            

            @Override
            public int getCount() 
                return mShowImageList.size();
            

            @Override
            public void setPrimaryItem(View container, int position, Object object) 

                //这里显示图片的数量还有设置图片是否被选中
                tvNumber.setText((position + 1) + "/" + mShowImageList.size());

                currentPosition = position;

                // 

                if (imageDataArrayList.get(position).isSelect()) 
                    cbSelect.setChecked(true);
                 else if (imageDataArrayList.get(position).isSelect() == false) 
                    cbSelect.setChecked(false);
                
                super.setPrimaryItem(container, position, object);
            

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) 

                container.removeView(mImageViews[position]);
            

            @Override
            public void notifyDataSetChanged() 
                super.notifyDataSetChanged();
            

            @Override
            public boolean isViewFromObject(View view, Object object) 
                //Log.e("nsc","isViewFromObject");
                return view == object;
            
        );
    
6、实现图片的编辑功能,可添加文字图片和直接手动绘制,还可以选择不同颜色实现如下图



实现手动在图片上绘制功能,先绘制图片出来

private void addBitmap()
        Matrix matrix = new Matrix();
        matrix.postScale(1, 1);
        mBitmap = BitmapFactory.decodeFile(imagePath).copy(Bitmap.Config.ARGB_8888, true);
        mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), matrix, true);
        canvas = new Canvas(mBitmap);
        mPaint = new Paint();
        if (mColor!=0) 
            mPaint.setColor(mColor);
        else 
            mPaint.setColor(Color.RED);
        
        mPaint.setAntiAlias(true);
        mPaint.setStrokeWidth(5);
        mPaint.setTextSize(30);
        ivShow.setImageMatrix(matrix);
        ivShow.setImageBitmap(mBitmap);
        canvas.drawBitmap(mBitmap, 0, 0, mPaint);
    
然后给图片添加监听,在手指移动的时候绘制滑动的线条,当两个手指同时按下的时候清除绘制。

ivShow.setOnTouchListener(new View.OnTouchListener() 

            float downx = 0;
            float downy = 0;
            float upx = 0;
            float upy = 0;

            @Override
            public boolean onTouch(View v, MotionEvent event) 

                switch (event.getAction()) 
                    case MotionEvent.ACTION_DOWN:
                        downx = event.getX();
                        downy = event.getY();
                        if (mColor!=0)
                            mPaint.setColor(mColor);
                        
                        break;
                    case MotionEvent.ACTION_MOVE:
                        upx = event.getX();
                        upy = event.getY();
                        canvas.drawLine(downx, downy, upx, upy, mPaint);
                        ivShow.invalidate();
                        downx = upx;
                        downy = upy;
                        break;

                    case MotionEvent.ACTION_POINTER_2_DOWN://两个手指点下的时候清屏
                        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
                        canvas.drawPaint(mPaint);
                        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
                        //Log.e(TAG,"ACTION_POINTER_2_DOWN");
                        addBitmap();

                        break;
                    default:
                        break;
                

                return true;
            
        );
当编辑完成后点完成会回到显示界面,整个app大概代码就这样,详细可自行下载代码查看

http://download.csdn.net/download/u011324501/10049415







以上是关于android 仿微信图片选择器的主要内容,如果未能解决你的问题,请参考以下文章

Android Studio仿微信图片选择器(增加删除)功能

Android 超高仿微信图片选择器 图片该这么载入

Android高仿微信图片选择上传工具

Android高仿微信图片选择上传工具

Android高仿微信图片选择上传工具

Kotlin 实现仿微信图片选择器(增删(长按无拖动))+RecyclerView+BaseQuickAdapter(官网github)的功能