[英]Android - Get an Image from the Gallery App?
当用户单击按钮时,我需要能够从图库中获取图像。
由于对此有很多答案,我的问题是如何做到这一点,将所选图像设置为RelativeLayout并且此 RelativeLayout 在另一个类中。
我的项目是这样设置的:我的 SettingsActivity 是按钮所在的位置,我的 MainActivity 是墙纸所在的位置。 当用户导航回 MainActivity 时,我需要将图像设置为 RelativeLayout。
我试过的代码:
设置活动:
changeWallpaper.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view1)
{
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
....
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();
editor.putBoolean(SETWALLPAPER, wallpaperSelection);
editor.commit();
}
}
主要活动:
isWallpaper = prefs.getBoolean(SETWALLPAPER, false);
...
if(isWallpaper == true)
{
Toast.makeText(MainActivity.this, "Setting BG", Toast.LENGTH_LONG).show();
wallpaperView.setBackgroundDrawable(new BitmapDrawable(bitmap));
}
谢谢
看起来您不是在选择图片时设置图片,而是在 onCreate() 内部
将您的if(..){}
放在onActivityResult()方法中并查看。
让我知道它是否有效。 使用else
并尝试查看结果。 若见,如果代码运行?
MainActivity什么都不做是因为活动不知道用户选择了什么
在 SettingActivity onActivityResult
,您可以将picturePath
存储在SharedPreferences
在 MainActivity onResume
,尝试获取图像的路径并将其转换为 Bitmap 并将其设置为背景可绘制
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.