我尝试从图库中选择背景图片并将其设置为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));
}
}
答案 0 :(得分:1)
你不能在RelativeLayout上做query()
。我想你要做的是setImageBitmap
,它将Drawable作为参数。
答案 1 :(得分:1)
这是因为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);
}
}