简体   繁体   English

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

[英]Why I am unable to set ImageBitmap to RelativeLayout here?

I'm trying to select a background image from gallery and set it as Activity background. 我正在尝试从图库中选择背景图像并将其设置为“ Activity背景”。 But the problem is here when I set RelativeLayout instead of ImageView , it gives me error on setImageBitmap , what;s the reason here? 但是问题出在这里,当我设置RelativeLayout而不是ImageView ,它给了我setImageBitmap错误,这是什么原因? Here's my code: I referred to this tutorial : http://viralpatel.net/blogs/pick-image-from-galary-android-app/ Thanks in advance! 这是我的代码:我已经参考了本教程: 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));

        }
    }

You can't do setImageBitmap on a RelativeLayout. 您不能在RelativeLayout上执行setImageBitmap I think what you want to do is setBackground which takes in a Drawable as parameter. 我认为您想做的是setBackground ,它以Drawable作为参数。

That is because RelativeLayout doesn't have a method called setImageBitmap . 这是因为RelativeLayout没有名为setImageBitmap的方法。 Referring to this link , you can use this to set it to your relative layout: 参考此链接 ,您可以使用它来将其设置为相对布局:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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