我正在使用照片選擇器來選擇圖像並將其寫入應用程序專用文件。我的大部分重要源代碼如下所示。一旦我按下一個按鈕並執行第一個圖像選擇意向,則它會成功更新圖像視圖。但是,一旦我再次按下圖像選擇按鈕(在同一活動中),則圖像視圖不會更新,除非我退出並重新啓動活動。所以我知道該圖像已成功保存,但爲什麼佈局中的ImageView不會刷新或更新?ImageView不刷新/反映更改
public void onResume() {
super.onResume();
ImageView myImageView = (ImageView)findViewById(R.id.contact_image);
if (hasImage) {
myImageView.setImageURI(Uri.fromFile(getFileStreamPath(TEMP_PHOTO_FILE)));
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PHOTO_PICKED:
if (resultCode == RESULT_OK) {
if (data != null) {
Bundle extras = data.getExtras();
if (extras != null) {
hasImage = true;
bmp = (Bitmap) extras.get("data");
}
}
}
break;
}
}
private OnClickListener mChooseImage = new OnClickListener() {
@Override
public void onClick(View v) {
try {
// Launch picker to choose photo for selected contact
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", ICON_SIZE);
intent.putExtra("outputY", ICON_SIZE);
intent.putExtra("scale", true);
intent.putExtra("return-data", false);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile()));
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(intent, PHOTO_PICKED);
} catch (ActivityNotFoundException e) {
// LOG THIS
}
}
};
private File getTempFile() {
try {
if (!hasImage) {
FileOutputStream fos = openFileOutput(TEMP_PHOTO_FILE, MODE_WORLD_WRITEABLE);
fos.close();
}
return getFileStreamPath(TEMP_PHOTO_FILE);
} catch (FileNotFoundException e) {
// To be logged later
return null;
} catch (IOException e) {
// To be logged later
return null;
}
}
根據活動結果,我將ImageView的圖像URI設置爲該文件。
第一次完成時,ImageView更改爲反映此情況。但是,如果我嘗試再次選擇圖像(相同的活動),ImageView將不會更新,直到我退出並重新輸入活動。我不確定爲什麼會發生這種情況,是否因爲我每次都試圖寫入temp.jpg?或者是否需要以某種方式刷新我的佈局以反映ImageView中的更改?
是否有一些代碼丟失?從你寫的內容來看,不需要打開輸出流到選定的圖像。 – 2010-12-16 08:26:53
我已經添加了大部分的源代碼。我還發現,如果我只是將意圖的值作爲位圖返回,則圖像視圖會成功更新。但是,我仍然想知道問題的根源。 – damonkashu 2010-12-16 10:21:29
那麼有什麼我不知道的ImageViews或圖像選擇器的意圖?在重新開始活動之前不反映變化的東西? – damonkashu 2010-12-17 08:43:09