导航菜单

页面标题

页面副标题

爱心e站 v1.0.0 - PhotoPickerActivity.java 源代码

正在查看: 爱心e站 v1.0.0 应用的 PhotoPickerActivity.java JAVA 源代码文件

本页面展示 JAVA 反编译生成的源代码文件,支持语法高亮显示。 仅供安全研究与技术分析使用,严禁用于任何非法用途。请遵守相关法律法规。


package com.newheyd.JZKFcanjiren.View.PhotoSelect;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.FileProvider;
import android.support.v4.content.Loader;
import android.support.v4.media.TransportMediator;
import android.support.v4.util.ArrayMap;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.newheyd.JZKFcanjiren.R;
import com.newheyd.JZKFcanjiren.View.PhotoSelect.entity.Photo;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class PhotoPickerActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
    private static final String ALL_PHOTO_DIR_NAME = "全部相片";
    public static final String IS_MULTI_SELECT = "is_multi_select";
    public static final String IS_SHOW_GIF = "is_show_gif";
    public static final String MAX_SELECT_SIZE = "max_select_size";
    public static final String SELECT_RESULTS = "default_select";
    public static final String SELECT_RESULTS_ARRAY = "default_select_array";
    private static final int TAKE_PHOTO = 100;
    private CommonMethod commonMethod;
    private List<Photo> currentDisplayPhotos;
    private FloatingActionButton fab;
    private boolean isMultiSelect;
    private boolean isShowGif;
    private int maxSize;
    private ArrayList<String> menuDirs = new ArrayList<>();
    private Map<String, List<Photo>> photoDirMap = new ArrayMap();
    private PhotoListAdapter photoListAdapter;
    private String resultPhotoUri;
    private ArrayList<String> resultPhotoUris;
    private RecyclerView rvContainer;
    private File takePhotoFile;
    private Toolbar toolbar;
    private TextView toolbarCustomView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestStoragePermission();
        this.commonMethod = new CommonMethod(this);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            this.isMultiSelect = bundle.getBoolean(IS_MULTI_SELECT, false);
            this.isShowGif = bundle.getBoolean(IS_SHOW_GIF, false);
            if (this.isMultiSelect) {
                this.resultPhotoUris = bundle.getStringArrayList(SELECT_RESULTS_ARRAY);
                if (this.resultPhotoUris == null) {
                    this.resultPhotoUris = new ArrayList<>();
                }
                this.maxSize = bundle.getInt(MAX_SELECT_SIZE, 0);
            } else {
                this.resultPhotoUri = bundle.getString(SELECT_RESULTS);
            }
        }
        setContentView(R.layout.photo_picker_activity);
        this.toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(this.toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayShowTitleEnabled(false);
            actionBar.setDisplayHomeAsUpEnabled(true);
            if (this.isMultiSelect) {
                this.toolbarCustomView = new TextView(this);
                this.toolbarCustomView.setTextColor(ViewCompat.MEASURED_STATE_MASK);
                this.toolbarCustomView.setTextSize(20.0f);
                this.toolbarCustomView.setText(String.format(Locale.getDefault(), "%d/%d", Integer.valueOf(this.resultPhotoUris.size()), Integer.valueOf(this.maxSize)));
                ActionBar.LayoutParams params = new ActionBar.LayoutParams(-2, -2);
                params.gravity = 1;
                actionBar.setCustomView(this.toolbarCustomView, params);
                actionBar.setDisplayShowCustomEnabled(true);
            }
        }
        this.toolbar.setTitle("图库");
        this.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PhotoPickerActivity.this.onBackPressed();
            }
        });
        this.rvContainer = (RecyclerView) findViewById(R.id.rvContainer);
        if (this.rvContainer != null) {
            this.rvContainer.setHasFixedSize(true);
            this.rvContainer.setLayoutManager(new GridLayoutManager(this, 3));
            this.rvContainer.setItemAnimator(new DefaultItemAnimator());
            this.photoListAdapter = new PhotoListAdapter(this, null);
            this.rvContainer.setAdapter(this.photoListAdapter);
        }
        this.fab = (FloatingActionButton) findViewById(R.id.tab);
        this.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PhotoPickerActivity.this.exitAndOk();
            }
        });
        getSupportLoaderManager().initLoader(0, null, this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        CursorLoader cursorLoader = new CursorLoader(this, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{"_id", "_data", "bucket_display_name"}, "mime_type=? or mime_type=?" + (this.isShowGif ? "or mime_type=?" : ""), this.isShowGif ? new String[]{"image/jpeg", "image/png", "image/gif"} : new String[]{"image/jpeg", "image/png"}, "date_added DESC");
        return cursorLoader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        List<Photo> photos;
        if (data != null && data.moveToFirst()) {
            List<Photo> allPhotoUris = new ArrayList<>();
            if (!this.photoDirMap.containsKey(ALL_PHOTO_DIR_NAME)) {
                this.photoDirMap.put(ALL_PHOTO_DIR_NAME, allPhotoUris);
            }
            if (!this.menuDirs.contains(ALL_PHOTO_DIR_NAME)) {
                this.menuDirs.add(ALL_PHOTO_DIR_NAME);
            }
            do {
                String photoDir = data.getString(data.getColumnIndex("bucket_display_name"));
                String photoUri = data.getString(data.getColumnIndex("_data"));
                if (!this.photoDirMap.containsKey(photoDir)) {
                    photos = new ArrayList<>();
                    this.photoDirMap.put(photoDir, photos);
                    this.menuDirs.add(photoDir);
                } else {
                    photos = this.photoDirMap.get(photoDir);
                }
                Photo photo = new Photo();
                if (this.resultPhotoUris != null && this.resultPhotoUris.contains(photoUri)) {
                    photo.isChecked = true;
                }
                photo.uri = photoUri;
                photos.add(photo);
                allPhotoUris.add(photo);
            } while (data.moveToNext());
            notifyChangePhotoList(ALL_PHOTO_DIR_NAME, allPhotoUris);
        }
    }

    private void notifyChangePhotoList(String subTitle, List<Photo> photos) {
        this.currentDisplayPhotos = photos;
        this.toolbar.setSubtitle(subTitle);
        this.photoListAdapter.setData(photos);
        this.photoListAdapter.notifyDataSetChanged();
    }

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem menuCamera = menu.add(0, R.id.menu_camera, 0, "拍照").setIcon(R.drawable.ic_photo_camera_black_24dp);
        MenuItemCompat.setShowAsAction(menuCamera, 2);
        SubMenu menuDir = menu.addSubMenu(0, R.id.menu_dir, 1, "目录").setIcon(R.drawable.ic_folder_open_black_24dp);
        MenuItemCompat.setShowAsAction(menuDir.getItem(), 2);
        super.onCreateOptionsMenu(menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Uri photoURI;
        if (item.getItemId() == 2131689472) {
            Intent takePictureIntent = new Intent("android.media.action.IMAGE_CAPTURE");
            this.takePhotoFile = createImageFile();
            if (this.takePhotoFile != null) {
                if (Build.VERSION.SDK_INT <= 23) {
                    photoURI = Uri.fromFile(this.takePhotoFile);
                } else {
                    photoURI = FileProvider.getUriForFile(this, ProviderUtil.getFileProviderName(this), this.takePhotoFile);
                }
                takePictureIntent.putExtra("output", photoURI);
                startActivityForResult(takePictureIntent, 100);
            } else {
                showSnackBar(getString(R.string.open_camera_fail));
            }
        } else if (item.getItemId() == 2131689473) {
            SubMenu subMenu = item.getSubMenu();
            subMenu.clear();
            Iterator<String> it = this.menuDirs.iterator();
            while (it.hasNext()) {
                String text = it.next();
                subMenu.add(0, 2, 0, text);
            }
        } else {
            String menuTitle = item.getTitle().toString();
            List<Photo> photos = this.photoDirMap.get(menuTitle);
            if (photos != null) {
                notifyChangePhotoList(menuTitle, photos);
            }
        }
        return super.onOptionsItemSelected(item);
    }

    private File createImageFile() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String imageFileName = "IMG_" + timeStamp;
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        if (!storageDir.exists() && !storageDir.mkdir()) {
            return null;
        }
        try {
            File file = File.createTempFile(imageFileName, ".jpg", storageDir);
            return file;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public void onPhotoListItemClick(View view) {
        this.fab.hide();
        int index = this.rvContainer.getChildViewHolder(view).getLayoutPosition();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        PhotoPreviewFragment f = PhotoPreviewFragment.newInstance(this.currentDisplayPhotos, index);
        ft.add(R.id.container, f, null);
        ft.addToBackStack(null);
        ft.commit();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.fab.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == -1 && this.takePhotoFile != null) {
            notifyMediaUpdate(this.takePhotoFile);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(IS_MULTI_SELECT, this.isMultiSelect);
        outState.putBoolean(IS_SHOW_GIF, this.isShowGif);
        outState.putInt(MAX_SELECT_SIZE, this.maxSize);
        if (this.takePhotoFile != null) {
            outState.putString("takePhotoPath", this.takePhotoFile.getAbsolutePath());
        }
        if (this.isMultiSelect) {
            outState.putStringArrayList(SELECT_RESULTS_ARRAY, this.resultPhotoUris);
        } else {
            outState.putString(SELECT_RESULTS, this.resultPhotoUri);
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        this.isMultiSelect = savedInstanceState.getBoolean(IS_MULTI_SELECT, false);
        this.isShowGif = savedInstanceState.getBoolean(IS_SHOW_GIF, false);
        this.maxSize = savedInstanceState.getInt(MAX_SELECT_SIZE, 0);
        String takePhotoPath = savedInstanceState.getString("takePhotoPath");
        if (!TextUtils.isEmpty(takePhotoPath)) {
            this.takePhotoFile = new File(takePhotoPath);
        } else {
            showSnackBar(getString(R.string.photo_save_fail));
        }
        if (this.isMultiSelect) {
            this.resultPhotoUris = savedInstanceState.getStringArrayList(SELECT_RESULTS_ARRAY);
        } else {
            this.resultPhotoUri = savedInstanceState.getString(SELECT_RESULTS);
        }
    }

    public void notifyMediaUpdate(File file) {
        Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
        Uri contentUri = Uri.fromFile(file);
        mediaScanIntent.setData(contentUri);
        sendBroadcast(mediaScanIntent);
    }

    public void exitAndOk() {
        Intent data = new Intent();
        if (this.isMultiSelect) {
            if (this.resultPhotoUris != null && !this.resultPhotoUris.isEmpty()) {
                data.putExtra(SELECT_RESULTS_ARRAY, this.resultPhotoUris);
            } else {
                showSnackBar("没有选择任何图片,请至少选择一张图片");
                return;
            }
        } else if (!TextUtils.isEmpty(this.resultPhotoUri)) {
            data.putExtra(SELECT_RESULTS, this.resultPhotoUri);
        } else {
            showSnackBar("没有选择任何图片,请选择一张图片");
            return;
        }
        setResult(-1, data);
        finish();
    }

    class PhotoListAdapter extends RecyclerView.Adapter<PhotoVH> {
        private final Activity activity;
        private final List<Photo> photos = new ArrayList();
        private View.OnClickListener checkedChangeListener = new View.OnClickListener() {
            private Photo lastPhoto;
            private int lastPosition;

            @Override
            public void onClick(View v) {
                CheckBox checkBox = (CheckBox) v;
                boolean checked = checkBox.isChecked();
                if (PhotoPickerActivity.this.isMultiSelect && PhotoPickerActivity.this.maxSize == PhotoPickerActivity.this.resultPhotoUris.size() && checked) {
                    PhotoPickerActivity.this.onAchieveMaxCount();
                    checkBox.setChecked(false);
                    return;
                }
                int position = ((Integer) v.getTag()).intValue();
                Photo photo = (Photo) PhotoListAdapter.this.photos.get(position);
                photo.isChecked = checked;
                if (!PhotoPickerActivity.this.isMultiSelect) {
                    if (this.lastPhoto != null) {
                        if (this.lastPhoto.equals(photo)) {
                            this.lastPhoto = null;
                            PhotoPickerActivity.this.resultPhotoUri = null;
                        } else {
                            this.lastPhoto.isChecked = false;
                            PhotoListAdapter.this.notifyItemChanged(this.lastPosition);
                            this.lastPhoto = photo;
                            this.lastPosition = position;
                        }
                    } else {
                        photo.isChecked = checked;
                        this.lastPhoto = photo;
                        this.lastPosition = position;
                    }
                    if (checked) {
                        PhotoPickerActivity.this.resultPhotoUri = photo.uri;
                        return;
                    }
                    return;
                }
                String uri = photo.uri;
                if (checked) {
                    if (!PhotoPickerActivity.this.resultPhotoUris.contains(uri)) {
                        PhotoPickerActivity.this.resultPhotoUris.add(uri);
                    }
                } else if (PhotoPickerActivity.this.resultPhotoUris.contains(uri)) {
                    PhotoPickerActivity.this.resultPhotoUris.remove(uri);
                }
                PhotoPickerActivity.this.toolbarCustomView.setText(String.format(Locale.getDefault(), "%d/%d", Integer.valueOf(PhotoPickerActivity.this.resultPhotoUris.size()), Integer.valueOf(PhotoPickerActivity.this.maxSize)));
            }
        };

        public PhotoListAdapter(Activity activity, List<Photo> photos) {
            if (photos != null) {
                this.photos.addAll(photos);
            }
            this.activity = activity;
        }

        @Override
        public int getItemCount() {
            return this.photos.size();
        }

        public void setData(List<Photo> photoUris) {
            this.photos.clear();
            this.photos.addAll(photoUris);
        }

        @Override
        public PhotoVH onCreateViewHolder(ViewGroup parent, int viewType) {
            Context context = parent.getContext();
            View itemView = LayoutInflater.from(context).inflate(R.layout.photo_img_item, parent, false);
            return new PhotoVH(itemView);
        }

        @Override
        public void onBindViewHolder(PhotoVH holder, int position) {
            ImageView photoView = holder.ivPhoto;
            Photo photo = this.photos.get(position);
            Glide.with(this.activity).load(photo.uri).thumbnail(0.1f).centerCrop().crossFade().diskCacheStrategy(DiskCacheStrategy.RESULT).into(photoView);
            CheckBox checkBox = holder.checkbox;
            checkBox.setChecked(photo.isChecked);
            checkBox.setTag(Integer.valueOf(position));
            checkBox.setOnClickListener(this.checkedChangeListener);
        }

        class PhotoVH extends RecyclerView.ViewHolder {
            CheckBox checkbox;
            ImageView ivPhoto;

            public PhotoVH(View itemView) {
                super(itemView);
                this.ivPhoto = (ImageView) itemView.findViewById(R.id.ivPhoto);
                this.checkbox = (CheckBox) itemView.findViewById(2131689584);
            }
        }
    }

    public void onAchieveMaxCount() {
        showSnackBar(getString(R.string.max_options));
    }

    private void showSnackBar(CharSequence text) {
        Snackbar.make(this.fab, text, -1).show();
    }

    public void requestStoragePermission() {
        if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, "android.permission.CAMERA") != 0) {
            ActivityCompat.requestPermissions(this, new String[]{"android.permission.CAMERA"}, TransportMediator.KEYCODE_MEDIA_RECORD);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case TransportMediator.KEYCODE_MEDIA_RECORD:
                if (grantResults[0] != 0) {
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(this, "android.permission.CAMERA")) {
                        this.commonMethod.dialogAndInset("开启相机权限");
                        break;
                    } else {
                        this.commonMethod.dialogAndInset("开启相机权限");
                        break;
                    }
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }
    }
}