如何在对话框中从图库中打开图像?

时间:2017-01-08 19:14:28

标签: android dialog image-gallery

我想在对话框中打开图库中的图片。

它没有对话框,但在对话框中失败。

任何人都可以帮我找到问题吗?感谢。

MainActivity.java

view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(MenuItem menuItem) {
        int item_id = menuItem.getItemId();
        switch (item_id) {
            case R.id.add_image:
                final Dialog imageDialog = new Dialog(MainActivity.this);
                imageDialog.setContentView(R.layout.add_image);

                //listen for clicks on Open Image Button
                Button addBtn = (Button) imageDialog.findViewById(R.id.addBtn);
                addBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                        intent.setType("image/*");
                        startActivityForResult(intent, IMAGE_CODE);
                    }
                });
                imageDialog.show();
                break;
        }
        return true;
    }
});

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == IMAGE_CODE && resultCode == RESULT_OK && null != data) {
        try {
            Uri uri = data.getData();
            ContentResolver cr = getContentResolver();

            Bitmap bitmap = MediaStore.Images.Media.getBitmap(cr, uri);

            ImageView image = (ImageView) findViewById(R.id.image);
            image.setImageBitmap(bitmap);
        }
        catch (Exception e) {
            Toast.makeText(this, "Please try again", Toast.LENGTH_LONG).show();
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}

1 个答案:

答案 0 :(得分:1)

问题似乎在以下几行 ImageView image =(ImageView)findViewById(R.id.image);

在这种情况下,

findViewById正在查找活动布局中的视图。而是在Dialog上使用findViewById。像

这样的东西

ImageView image =(ImageView)dialogLayout.findViewById(R.id.image);