为什么我无法在这里将 ImageBitmap 设置为 RelativeLayout?

Why I am unable to set ImageBitmap to RelativeLayout here?

我正在尝试 select 图库中的背景图片并将其设置为 Activity 背景。但是问题出在这里,当我设置 RelativeLayout 而不是 ImageView 时,它在 setImageBitmap 上给我错误,这是什么原因?这是我的代码:我参考了本教程:http://viralpatel.net/blogs/pick-image-from-galary-android-app/提前致谢!

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

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

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

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            ImageView imageView = (ImageView) findViewById(R.id.background);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

        }
    }

您不能在 RelativeLayout 上执行 setImageBitmap。我想你想要做的是 setBackground 它接受一个 Drawable 作为参数。

那是因为 RelativeLayout 没有名为 setImageBitmap 的方法。 参考这个link,你可以用它来设置你的相对布局:

File f = new File(getRealPathFromURI(path));  
Drawable d = Drawable.createFromPath(f.getAbsolutePath());
mRelativeLayout.setBackground(d);

private String getRealPathFromURI(Uri contentURI) {
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) { // Source is Dropbox or other similar local file path
            return contentURI.getPath();
        } else { 
            cursor.moveToFirst(); 
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
            return cursor.getString(idx); 
        }
    }