長按ImageView開啟選取器取得圖片Uri


加入長按事件

    private ImageView imageView;
...
onCreate
...
        imageView = findViewById(R.id.imageView);
        imageView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                pickFromGallery();
                return true;
            }
        });

啟動圖片選取器

    /**
     * @ref https://androidclarified.com/pick-image-gallery-camera-android/
     */
    final static int GALLERY_REQUEST_CODE = 0x1000;

    private void pickFromGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK); // launch gallery app
        //Intent intent = new Intent(Intent.ACTION_GET_CONTENT); // launch document app, more complicate UI
        intent.setType("image/*");
        //String[] mimeTypes = {"image/jpeg", "image/png"};
        //intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        //intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        startActivityForResult(intent, GALLERY_REQUEST_CODE);
    }

處理取得的圖片Uri

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == Activity.RESULT_OK)
            switch (requestCode) {
                case GALLERY_REQUEST_CODE: {
                    Uri imgUri = null==data? null : data.getData();
                    if (null != imgUri) {
                        // imgUri has a prefix content://, is not same as file path
                        imageView.setImageURI(imgUri);
                        imageView.setTag(imgUri);
                    }
                    String msg = String.format("selected img URI:%s", imgUri);
                    Log.i(TAG, msg);
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
                    break;
                }
            }
        super.onActivityResult(requestCode, resultCode, data);
    }


留言