我正在使用照片选择器意图选择图像并将其写入应用程序专用文件.我的大部分重要源代码如下所示.按下按钮并执行第一个图像选择意图后,它会成功更新图像视图.但是,一旦我再次按下图像选择按钮(在同一活动中),图像视图就不会更新,除非我退出并重新启动活动.所以我知道图像已成功保存,但为什么布局中的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;
}
}
Run Code Online (Sandbox Code Playgroud)
根据活动结果,我将ImageView的图像URI设置为此文件.
首次完成时,ImageView会更改以反映此情况.但是,如果我再次尝试选择图像(相同的活动),ImageView将不会更新,直到我退出并重新进入活动.我不确定为什么会这样,是因为我每次都想写入temp.jpg?或者我是否需要以某种方式刷新我的布局以反映ImageView中的更改?
cla*_*esv 19
通过ImageView源代码判断,如果使用相同的URI调用setImageURI,ImageView将不会重新加载图像.您可以尝试通过将图像写入另一个文件来更改URI.
小智 15
如果"new"URI与旧版本相同,则ImageView不会重绘."View.invalidate()"无效.要"强制"更新,您可以执行以下操作:
public void onResume() {
super.onResume();
ImageView myImageView = (ImageView)findViewById(R.id.contact_image);
if (hasImage) {
myImageView.setImageDrawable(null); // <--- added to force redraw of ImageView
myImageView.setImageURI(Uri.fromFile(getFileStreamPath(TEMP_PHOTO_FILE)));
}
}
Run Code Online (Sandbox Code Playgroud)
invalidate()无效.试试黑客:
imageView.setImageURI(null);
imageView.setImageURI(newUri);
Run Code Online (Sandbox Code Playgroud)
要强制重绘您的小部件/视图,只需调用View.invalidate();
| 归档时间: |
|
| 查看次数: |
22973 次 |
| 最近记录: |