[英]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.