【问题标题】:show image form gallery in fragment dont work在片段中显示来自画廊的图像不起作用
【发布时间】:2017-04-03 12:22:50
【问题描述】:

我从我的片段之一打开画廊,但在我从画廊中选择图像之后 图像没有显示给我。

在onActivityResult 我在这一行的rootview 中有错误: ImageView imgView = (ImageView) rootview.findViewById(R.id.imgView); 我用 toast 进行测试以向我展示所选的图像路径,但是 它没有显示路径。

这是我的片段代码:

public class Share_Page extends Fragment implements View.OnClickListener {

    private static final int RESULT_OK = 1;
    String path="";
    String imgPath, fileName;
    private Button home_page,search_page;
    private static int RESULT_LOAD_IMG = 1;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootview = inflater.inflate(R.layout.share, container, false);
        home_page = (Button) rootview.findViewById(R.id.home_page);
        search_page = (Button) rootview.findViewById(R.id.search_page);


        rootview.findViewById(R.id.buttonLoadPicture).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadImagefromGallery();
            }
        });




        btn_click();

        return rootview;
    }
    public void loadImagefromGallery() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {

            if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                    && null != data) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };

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

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imgPath = cursor.getString(columnIndex);
                cursor.close();
                //ImageView imgView = (ImageView) findViewById(R.id.imgView);
                ImageView imgView = (ImageView) rootview.findViewById(R.id.imgView);
                imgView.setImageBitmap(BitmapFactory
                        .decodeFile(imgPath));
                String fileNameSegments[] = imgPath.split("/");
                fileName = fileNameSegments[fileNameSegments.length - 1];
                path=imgPath;

            } else {
                Toast.makeText(getActivity(), "image not select",
                        Toast.LENGTH_LONG).show();
                imgPath="2";
            }
        } catch (Exception e) {
            Toast.makeText(getActivity(), "error`enter code here`...!", Toast.LENGTH_LONG)
                    .show();
        }
    }

【问题讨论】:

  • 你给我投反对票是为了什么?它不是重复的问题
  • define ImageView imgView = (ImageView) rootview.findViewById(R.id.imgView);在 onCreateView 方法中并从 onActivityResult 中删除
  • 我这样做了,但在 onActivityResult 中是未知的
  • 将ImageView imgView设为全局并在OnCreateView()中初始化
  • 检查这个 onActivityResult() stackoverflow.com/questions/6147884/…

标签: java android android-fragments


【解决方案1】:

此方法用于意图打开图库并选择图像:

public void loadImagefromGallery(View view) {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityIfNeeded(galleryIntent, RESULT_LOAD_IMG);
    }

这是选取图像后的结果。如您所见,我使用图像来更改背景,您可以将其放入 imageView 或您想要的任何东西中

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                    && null != data) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                assert cursor != null;
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String imgDecodableString = cursor.getString(columnIndex);
                cursor.close();
                Drawable d = new BitmapDrawable(getResources(), imgDecodableString);
                relativeLayout.setBackground(d);
            } else {
                Toast.makeText(this, "You haven't picked Image",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                    .show();
        }
}

另外请记得在 Manifest 中添加权限

示例如何使用权限运行时,将其粘贴到活动中

 private static final int REQUEST_CODE_EXTERNAL_STORAGE = 1;
    private static final int REQUEST_CODE_CAMERA = 2;
private static int RESULT_LOAD_IMG = 1;
@TargetApi(23)
    public void checkCameraPermission(){
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
            return;
        }
        if (this.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[] {Manifest.permission.CAMERA}, REQUEST_CODE_CAMERA);
        }
    }

    @TargetApi(23)
    public void checkStoragePermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return;
        }
        if (this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager
                .PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    REQUEST_CODE_EXTERNAL_STORAGE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_EXTERNAL_STORAGE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "Thanks for your permission", LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "We need your permission to save image",
                            LENGTH_SHORT).show();
                }
                break;
            case REQUEST_CODE_CAMERA:
                if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(this, "Thanks for your permission", LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "We need your permission to start SOS",
                            LENGTH_SHORT).show();
                }
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }
}

如果你想检查片段的权限,你应该这样做:

((Activity) getContext()).checkAnyPermission();

你应该在打开画廊后检查一下

【讨论】:

  • 我使用你的代码,但在这一行中 relativeLayout.setBackground(d);告诉我 relativeLayout 的错误
  • 我应该添加 imgView 而不是 relativeLayout?
  • 程序正在运行,但是当我选择图像后启动程序时,此错误显示:
  • "你还没有选择图片"
猜你喜欢
  • 2014-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 2015-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多