PhotoPickerDemo【PhotoPicker0.9.8的個性化修改以及使用(內部glide版本號是3.7.0)】

版權聲明:本文爲HaiyuKing原創文章,轉載請註明出處!html

前言

本Demo使用的是PhotoPicker 0.9.8版本,屬於比較舊的版本,裏面集成的glide版本號是3.7.0。本篇文章主要是留做記錄。java

在項目中使用建議使用《PhotoPickerNewDemo【PhotoPicker0.9.12的個性化修改以及使用(內部glide版本號是4.1.1)】android

效果圖

    

代碼分析

在原有的代碼基礎上根據實際項目需求進行了部分修改:git

一、對MediaStoreHelper進行了優化【解決dialogFragment中顯示問題】

二、添加NewImagePagerDialogFragment.java【和ImagePagerFragment.java代碼相似,不一樣的是多了頂部導航欄】【用於獨立出來進行圖片預覽對話框】

三、添加NewPhotoPickerFragment.java【基本上等同於PhotoPickerFragment,可是區別在於預覽圖片打開的是NewImagePagerDialogFragment,並且多了一個狀態值:是否全屏顯示預覽界面】【用於獨立出來做爲Fragment集成到自定義Activity中】

四、修改顏色、高度和替換部分圖片

使用步驟

1、項目組織結構圖

注意事項:github

一、  導入類文件後須要change包名以及從新import R文件路徑緩存

二、  Values目錄下的文件(strings.xml、dimens.xml、colors.xml等),若是項目中存在,則複製裏面的內容,不要整個覆蓋app

2、導入步驟

(1)將PhotoPicker導入到項目中

(2)解決Plugin with id 'com.novoda.bintray-release' not found.問題

在項目的build.gradle文件中添加如下代碼ide

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        //解決PhotoPicker的Plugin with id 'com.novoda.bintray-release' not found. classpath 'com.novoda:bintray-release:0.5.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

3、使用方法

(1)在app的build.gradle文件中引用photopicker

由於Demo中使用到了RecyclerVIew,因此還須要在app的build.gradle文件中引用recyclerview【版本號和appcompat保持一致函數

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.why.project.photopickerdemo"
        minSdkVersion 16
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    //photopicker implementation project(':PhotoPicker')
    
    //RecyclerView compile 'com.android.support:recyclerview-v7:27.1.1'
    
}

(2)演示調用寫法

一、在項目中實現Recyclerview基本數據展示【比較簡單,省略】【或者參考《Android快速開發經常使用知識點系列目錄》下的RecyclerView篇章相關文章】工具

注意:由於PhotoPicker中已經引用了Glide3.7.0,因此PictureAdapter.java中能夠直接使用Glide

package com.why.project.photopickerdemo.adapter;

import android.content.Context;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.why.project.photopickerdemo.R;
import com.why.project.photopickerdemo.bean.PictureBean;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by HaiyuKing
 * Used 照片網格適配器
 */

public class PictureAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

    private static final String TAG = PictureAdapter.class.getSimpleName();

    /**上下文*/
    private Context myContext;
    /**自定義列表項標題集合*/
    private ArrayList<PictureBean> listitemList;

    final static int TYPE_ADD = 1;
    final static int TYPE_PHOTO = 2;

    public final static int MAX = 15;//總數目,這裏根據實際狀況設置,設置100基本上代表無限制了

    /*
    * 構造函數
    */
    public PictureAdapter(Context context, ArrayList<PictureBean> itemlist) {
        myContext = context;
        listitemList = itemlist;
    }

    /**
     * 獲取總的條目數
     */
    @Override
    public int getItemCount() {
        Log.w(TAG,"{getItemCount}listitemList.size()="+listitemList.size());
        int count = listitemList.size();
        if (count > MAX) {
            count = MAX;
        }
        count = count + 1;
        return count;
    }

    @Override
    public int getItemViewType(int position) {
        Log.w(TAG,"{getItemViewType}position="+position);
        Log.w(TAG,"{getItemViewType}listitemList.size()="+listitemList.size());
        return (position == listitemList.size()) ? TYPE_ADD : TYPE_PHOTO;
    }

    /**
     * 建立ViewHolder
     */
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if(viewType == TYPE_ADD) {
            View viewfoot = LayoutInflater.from(myContext).inflate(R.layout.pic_grid_foot_item, parent, false);
            ItemFootViewHolder itemfootViewHolder = new ItemFootViewHolder(viewfoot);
            return itemfootViewHolder;
        } else if(viewType == TYPE_PHOTO) {
            View view = LayoutInflater.from(myContext).inflate(R.layout.pic_grid_item, parent, false);
            ItemViewHolder itemViewHolder = new ItemViewHolder(view);
            return itemViewHolder;
        }
        return null;
    }

    /**
     * 聲明列表項ViewHolder*/
    static class ItemViewHolder extends RecyclerView.ViewHolder
    {
        public ItemViewHolder(View view)
        {
            super(view);
            griditemLayout = (LinearLayout) view.findViewById(R.id.griditemLayout);
            griditemimgLayout = (RelativeLayout) view.findViewById(R.id.griditemimgLayout);
            grid_img = (ImageView) view.findViewById(R.id.grid_img);
            grid_img_state = (TextView) view.findViewById(R.id.grid_img_state);
        }

        LinearLayout griditemLayout;
        RelativeLayout griditemimgLayout;
        ImageView grid_img;

        TextView grid_img_state;
    }

    /**
     * 聲明最後一個ViewHolder*/
    static class ItemFootViewHolder extends RecyclerView.ViewHolder
    {
        public ItemFootViewHolder(View view)
        {
            super(view);
            gridfootitemLayout = (RelativeLayout) view.findViewById(R.id.gridfootitemLayout);
        }
        RelativeLayout gridfootitemLayout;
    }

    /**
     * 將數據綁定至ViewHolder
     */
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int index) {

        if(viewHolder instanceof ItemViewHolder){
            PictureBean listItemModel = listitemList.get(index);
            final ItemViewHolder itemViewHold = ((ItemViewHolder)viewHolder);

            Uri uri = Uri.fromFile(new File(listItemModel.getPicPath()));

            Glide.with(myContext) .load(uri) //設置等待時的圖片
 .placeholder(R.drawable.img_loading) //設置加載失敗後的圖片顯示
 .error(R.drawable.img_error) //默認淡入淡出動畫
 .crossFade() //緩存策略,跳過內存緩存【此處應該設置爲false,不然列表刷新時會閃一下】
                    .skipMemoryCache(false) //緩存策略,硬盤緩存-僅僅緩存最終的圖像,即下降分辨率後的(或者是轉換後的)
 .diskCacheStrategy(DiskCacheStrategy.ALL) //設置圖片加載的優先級
 .priority(Priority.HIGH) .into(itemViewHold.grid_img); 
            itemViewHold.grid_img_state.setText("(" + (index+1) + "/" + listitemList.size() + ")");

            //若是設置了回調,則設置點擊事件
            if (mOnItemClickLitener != null)
            {
                itemViewHold.grid_img.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int position = itemViewHold.getLayoutPosition();//在增長數據或者減小數據時候,position和index就不同了
                        mOnItemClickLitener.onItemClick(view,position);
                    }
                });
            }
        }else if(viewHolder instanceof ItemFootViewHolder){
            final ItemFootViewHolder itemFootViewHold = ((ItemFootViewHolder)viewHolder);
            //若是設置了回調,則設置點擊事件
            if (mOnItemClickLitener != null)
            {
                itemFootViewHold.gridfootitemLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mOnItemClickLitener.onItemAddClick();
                    }
                });
            }
        }

    }

    /**
     * 添加Item--用於動畫的展示*/
    public void addItem(int position,PictureBean itemModel) {
        listitemList.add(position,itemModel);
        notifyItemInserted(position);
    }
    /**
     * 刪除Item--用於動畫的展示*/
    public void removeItem(int position) {
        listitemList.remove(position);
        notifyItemRemoved(position);
    }

    /*=====================添加OnItemClickListener回調================================*/
    public interface OnItemClickLitener
    {
        /**圖片的點擊事件*/
        void onItemClick(View view,int position);
        /**添加的點擊事件*/
        void onItemAddClick();
    }

    private OnItemClickLitener mOnItemClickLitener;

    public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener)
    {
        this.mOnItemClickLitener = mOnItemClickLitener;
    }

    //返回當前圖片集合的全部路徑集合【用於預覽】
    public List<String> getAllPhotoPaths() {
        List<String> allPhotoPaths = new ArrayList<String>(listitemList.size());
        for (PictureBean  pictureBean: listitemList) {
            allPhotoPaths.add(pictureBean.getPicPath());
        }
        return allPhotoPaths;
    }

}

二、在代碼中調用【橙色標記的是recyclerView常規寫法黃色標記的是PhotoPicker的調用綠色標記是打開自定義圖片預覽對話框NewImagePagerDialogFragment紫色標記的是自定義選圖對話框界面

package com.why.project.photopickerdemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.why.project.photopickerdemo.adapter.PictureAdapter;
import com.why.project.photopickerdemo.bean.PictureBean;
import com.why.project.photopickerdemo.utils.Globals;

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

import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.fragment.NewImagePagerDialogFragment;
import me.iwf.photopicker.utils.PermissionsUtils;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private RecyclerView mRecyclerView; private ArrayList<PictureBean> mPictureBeansList; private PictureAdapter mPictureAdapter; private ArrayList<String> selPhotosPath = null;//選中的圖片路徑集合

    private Button mOpenPicDialog;

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

        initViews();
        initDatas();
        initEvents();
    }

    private void initViews() {
        mRecyclerView = findViewById(R.id.picture_grid);
        mOpenPicDialog = findViewById(R.id.btn_openPicDialog);
    }

    private void initDatas() {
        selPhotosPath = new ArrayList<String>(); //=============圖片九宮格=========================
        mPictureAdapter = null; mPictureBeansList = new ArrayList<PictureBean>(); //設置佈局管理器
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3); mRecyclerView.setLayoutManager(gridLayoutManager); if(mPictureAdapter == null){ //設置適配器
            mPictureAdapter = new PictureAdapter(this, mPictureBeansList); mRecyclerView.setAdapter(mPictureAdapter); //添加分割線 //設置添加刪除動畫 //調用ListView的setSelected(!ListView.isSelected())方法,這樣就能及時刷新佈局
            mRecyclerView.setSelected(true); }else{ mPictureAdapter.notifyDataSetChanged(); }
    }

    private void initEvents() {
        //圖片九宮格點擊事件
        mPictureAdapter.setOnItemClickLitener(new PictureAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View v,int position) {
                //打開自定義的圖片預覽對話框
                List<String> photos = mPictureAdapter.getAllPhotoPaths(); int[] screenLocation = new int[2]; v.getLocationOnScreen(screenLocation); NewImagePagerDialogFragment newImagePagerDialogFragment = NewImagePagerDialogFragment.getInstance(MainActivity.this,photos,position,screenLocation, v.getWidth(), v.getHeight(),false); newImagePagerDialogFragment.show(getSupportFragmentManager(),"preview img");
            }

            @Override
            public void onItemAddClick() {
                PhotoPicker.builder() .setPhotoCount(mPictureAdapter.MAX) .setGridColumnCount(3) //.setSelected(selPhotosPath)
                        .start(MainActivity.this, Globals.CHOOSE_PIC_REQUEST_CODE);
            }
        });

        //按鈕的點擊事件
        mOpenPicDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (PermissionsUtils.checkReadStoragePermission(MainActivity.this)) {//調用PhotoPicker中的運行時權限申請工具類,在這裏也可使用其餘運行時權限申請庫
                    Bundle bundle = new Bundle(); bundle.putInt(SelectPictureDialog.EXTRA_MAX_COUNT, 1); SelectPictureDialog selectPictureDialog = SelectPictureDialog.getInstance(MainActivity.this, bundle); selectPictureDialog.setOnSelPicDialogConfirmClickListener(new SelectPictureDialog.OnSelPicDialogConfirmClickListener() { @Override public void onConfirmClick(ArrayList<PictureBean> selectedPhotoList) { String path = ""; if (selectedPhotoList.size() > 0) { path = selectedPhotoList.get(0).getPicPath(); } Toast.makeText(MainActivity.this, "path=" + path, Toast.LENGTH_SHORT).show(); } }); selectPictureDialog.show(getSupportFragmentManager(), "previewWithScreen"); }
            }
        });
    }

    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Log.w(TAG, "{onActivityResult}resultCode="+resultCode); Log.w(TAG, "{onActivityResult}requestCode="+requestCode); if (resultCode == Activity.RESULT_OK) { //選擇照片
            if(requestCode == Globals.CHOOSE_PIC_REQUEST_CODE){ if (data != null) { selPhotosPath = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS); } if (selPhotosPath != null) { //下面的代碼主要用於這樣一個場景,就是註釋了.setSelected(selPhotosPath)以後,還想要保證選擇的圖片不重複
                    /*for(String path : selPhotosPath){ Log.w(TAG,"path="+path);///storage/emulated/0/tempHxzk/IMG_1498034535796.jpg boolean existThisPic = false; for(int i=0;i<mPictureBeansList.size();i++){ if(path.equals(mPictureBeansList.get(i).getPicPath())){ //若是新選擇的圖片集合中存在以前選中的圖片,那麼跳過去 existThisPic = true; break; } } if(! existThisPic){ PictureBean pictureBean = new PictureBean(); pictureBean.setPicPath(path); pictureBean.setPicName(getFileName(path)); //去掉總數目的限制,這裏經過增大MAX的數字來實現 if (mPictureBeansList.size() < mPictureAdapter.MAX) { mPictureBeansList.add(pictureBean); } else { Toast.makeText(MainActivity.this, "最多能夠選擇" + mPictureAdapter.MAX + "張圖片", Toast.LENGTH_SHORT).show(); break; } } }*/

                    //是常規操做,和上面的代碼不可共存
                    for (String path : selPhotosPath) { PictureBean pictureBean = new PictureBean(); pictureBean.setPicPath(path); pictureBean.setPicName(Globals.getFileName(path)); //去掉總數目的限制,這裏經過增大MAX的數字來實現
                        if (mPictureBeansList.size() < mPictureAdapter.MAX) { mPictureBeansList.add(pictureBean); } else { Toast.makeText(MainActivity.this, "最多能夠選擇" + mPictureAdapter.MAX + "張圖片", Toast.LENGTH_SHORT).show(); break; } } mPictureAdapter.notifyDataSetChanged(); } } } }

}

三、SelectPictureDialog中主要集成了NewPhotoPickerFragment,這裏只是一個簡單的寫法,原本是有一個選項卡功能的,這裏作了簡化

package com.why.project.photopickerdemo;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.why.project.photopickerdemo.bean.PictureBean;
import com.why.project.photopickerdemo.utils.Globals;

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

import me.iwf.photopicker.fragment.NewPhotoPickerFragment;

/**
 * Created by HaiyuKing
 * Used 選擇圖片對話框
 */

public class SelectPictureDialog extends DialogFragment {
    private static final String TAG = SelectPictureDialog.class.getSimpleName();

    /**View實例*/
    private View myView;
    /**context實例*/
    private Context mContext;
    /**標記:用來表明是從哪一個界面打開的這個對話框*/
    private String mTag;

    /**完成文本*/
    private TextView mConfirmTv; public static final String EXTRA_MAX_COUNT = "maxCount"; public static final int DEFAULT_MAX_COUNT = 1;//默認只能選擇一個圖片

    private boolean previewEnabled = true;//是否可預覽
    private boolean showGif = false;//是否顯示gif
    private int columnNumber = 3;//一行顯示多少列
    private int maxCount = 1;//最大可選擇的數目
    private Boolean fullscreen = false;//是否全屏展示預覽界面的標誌

    private FragmentManager fragmentManager;//碎片管理器
    private NewPhotoPickerFragment mLocalPicFragment; public static SelectPictureDialog getInstance(Context mContext, Bundle bundle)
    {
        SelectPictureDialog selectPictureDialog = new SelectPictureDialog();
        selectPictureDialog.mContext = mContext;
        selectPictureDialog.maxCount = bundle.getInt(EXTRA_MAX_COUNT,DEFAULT_MAX_COUNT);

        return selectPictureDialog;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.w(TAG,"{onCreate}");

        setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_NoTitleBar_Fullscreen);//全屏(在狀態欄底下)
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.w(TAG,"{onCreateView}");

        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(0));//設置背景爲透明,而且沒有標題
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉標題欄
        //設置窗體全屏
        getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        myView = inflater.inflate(R.layout.dialog_select_picture, container, false);
        return myView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        Log.w(TAG,"{onActivityCreated}");

        //初始化控件以及設置
        initView();
        //初始化數據
        initDatas();
        //初始化事件
        initEvent();

        //初始化碎片管理器
        fragmentManager = getChildFragmentManager();//必須使用getChildFragmentManager,不然子Fragment中沒法使用getParentFragment獲取父fragment

    }

    /**
     * 設置寬度和高度值,以及打開的動畫效果
     */
    @Override
    public void onStart() {
        super.onStart();
        if(mTag.equals("previewWithScreen")){//對話框全屏顯示,預覽圖片也是全屏顯示
            fullscreen = true;
            //設置對話框的寬高,必須在onStart中
            Window window = this.getDialog().getWindow();
            window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);//全屏(蓋住狀態欄)
            window.setGravity(Gravity.BOTTOM);//設置在底部
            //打開的動畫效果--縮放+漸隱
        }else{
            fullscreen = false;
            //設置對話框的寬高,必須在onStart中
            DisplayMetrics metrics = new DisplayMetrics();
            this.getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
            Window window = this.getDialog().getWindow();
            window.setLayout(metrics.widthPixels, metrics.heightPixels - getStatusBarHeight(mContext));
            window.setGravity(Gravity.BOTTOM);//設置在底部
            //打開的動畫效果--縮放+漸隱
        }
    }

    /**獲取狀態欄的高度*/
    private int getStatusBarHeight(Context context) {
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        return context.getResources().getDimensionPixelSize(resourceId);
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        ShowFragment();
    }

    private void initView() {
        mConfirmTv = (TextView) myView.findViewById(R.id.nav_selpic_edit_save);
    }

    private void initDatas() {
        mTag = this.getTag();
    }

    private void initEvent() {
        //完成圖標
        mConfirmTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //返回界面,並傳遞值回去
                ArrayList<PictureBean> selectedPhotoList = new ArrayList<PictureBean>();

                if(maxCount <= 1){
                    ArrayList<String> selectedPhotos = new ArrayList<String>();
                    if(mLocalPicFragment != null) {
                        selectedPhotos = mLocalPicFragment.getPhotoGridAdapter().getSelectedPhotoPaths();
                    }
                    String imgPath = selectedPhotos.get(0);
                    PictureBean pictureBean = new PictureBean();
                    pictureBean.setPicPath(imgPath);
                    pictureBean.setPicName(Globals.getFileName(imgPath));
                    selectedPhotoList.add(pictureBean);
                }else{
                    ArrayList<String> selectedPhotos = new ArrayList<String>();
                    if(mLocalPicFragment != null) {
                        selectedPhotos = mLocalPicFragment.getPhotoGridAdapter().getSelectedPhotoPaths();
                    }
                    for(String path : selectedPhotos){
                        PictureBean pictureBean = new PictureBean();
                        pictureBean.setPicPath(path);
                        pictureBean.setPicName(Globals.getFileName(path));
                        selectedPhotoList.add(pictureBean);
                    }
                }

                backWithResult(selectedPhotoList);
            }
        });
        //剛開始設置不可點擊【必須在setOnclick事件以後,不然不起做用】
        changeConfirmState(false);
    }

    private void ShowFragment() {
        //開啓一個事務
        FragmentTransaction transcation = fragmentManager.beginTransaction();
        if(mLocalPicFragment == null){
            mLocalPicFragment = NewPhotoPickerFragment.getInstance(true, showGif, previewEnabled, columnNumber, maxCount, null,fullscreen);
            initLocalFragmentAdapterItemCheckListener();//初始化本地圖片碎片界面的列表項的複選框圖標點擊事件
            transcation.add(R.id.center_layout, mLocalPicFragment);
        }else{
            transcation.show(mLocalPicFragment);
        }
        transcation.commitAllowingStateLoss();
    }

    //本地圖片的選擇監聽
    private void initLocalFragmentAdapterItemCheckListener() { //本地圖片的選擇的監聽事件
        mLocalPicFragment.setOnOnLocalPhotoCheckListener(new NewPhotoPickerFragment.OnLocalPhotoCheckListener() { @Override public boolean onItemCheck(int position, String imgId, String imgName, String imgPath, int selectedItemCount) { //若是選中的數目小於0,則頂部導航欄右側的完成文本,不可點擊
                if(selectedItemCount > 0){ changeConfirmState(true); }else{ changeConfirmState(false); } //若是單選,那麼選中的圖片路徑集合確定只有一個
                if (maxCount <= 1) { List<String> photos = mLocalPicFragment.getPhotoGridAdapter().getSelectedPhotos(); if (!photos.contains(imgPath)) {//若是點擊的當前選中的圖片,則取消選中狀態
                        photos.clear();//清空選中的圖片集合
 mLocalPicFragment.getPhotoGridAdapter().notifyDataSetChanged(); } return true; } if (selectedItemCount > maxCount) { Toast.makeText(mContext,getString(R.string.over_max_count_tips, maxCount),Toast.LENGTH_SHORT).show(); return false; } mConfirmTv.setText(getString(R.string.done_with_count, selectedItemCount, maxCount));//更改導航欄右側的 完成(1/9)
                return true; } }); } //更換完成文本的點擊狀態
    private void changeConfirmState(boolean canClick){
        if(canClick){
            mConfirmTv.setClickable(true);
            mConfirmTv.setTextColor(getResources().getColor(R.color.nav_done_text_color));
        }else{
            mConfirmTv.setClickable(false);
            mConfirmTv.setTextColor(getResources().getColor(R.color.nav_done_ennable_text_color));
        }
    }


    private void backWithResult(ArrayList<PictureBean> photosList) {
        dismiss();
        if(mOnSelPicDialogConfirmClickListener != null){
            mOnSelPicDialogConfirmClickListener.onConfirmClick(photosList);
        }
    }

    /*=====================添加OnConfirmClickListener回調================================*/
    private OnSelPicDialogConfirmClickListener mOnSelPicDialogConfirmClickListener;

    public void setOnSelPicDialogConfirmClickListener(OnSelPicDialogConfirmClickListener mOnSelPicDialogConfirmClickListener)
    {
        this.mOnSelPicDialogConfirmClickListener = mOnSelPicDialogConfirmClickListener;
    }

    public interface OnSelPicDialogConfirmClickListener {
        void onConfirmClick(ArrayList<PictureBean> selectedPhotoList);
    }
}

混淆配置

# PhotoPicker混淆
# Glide
-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
    **[] $VALUES;
    public *;
}
# support-v7-appcompat
-keep public class android.support.v7.widget.** { *; }
-keep public class android.support.v7.internal.widget.** { *; }
-keep public class android.support.v7.internal.view.menu.** { *; }
-keep public class * extends android.support.v4.view.ActionProvider {
    public <init>(android.content.Context);
}
# support-design
-dontwarn android.support.design.**
-keep class android.support.design.** { *; }
-keep interface android.support.design.** { *; }
-keep public class android.support.design.R$* { *; }

參考資料

donglua/PhotoPicker

項目demo下載地址

https://github.com/haiyuKing/PhotoPickerDemo

相關文章
相關標籤/搜索