简体   繁体   中英

How to open an Image from gallery in a dialog?

I'd like to open an image from gallery in a dialog.

It's works without a dialog, but fails within a dialog.

Can anyone help me find the problem? Thanks.


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);
}

The problem seems to be in the following line ImageView image = (ImageView) findViewById(R.id.image);

findViewById in this case is looking for views inside your activity layout. Instead use findViewById on your Dialog. Something like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM