在我的应用程序中,我在名为Day的活动中设置了图像。现在,当用户想要更改图像时,他选择按钮并从图库中选择图像。这是代码:
private void choosePhoto() {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, REQUEST_IMAGE_PICK);
}
当用户选择图像时,我会查看onActivityResult,他选择了什么,并希望将其设置为新的ImageView,但它不会更新。我的意思是,旧图像仍然可见,但不是新图像。我必须退出并再次进入活动以查看更改。 这是onActivityResult:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_PICK && resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String realImagePath = PhotoUtils.getRealPathFromURI(this, selectedImage);
Bitmap imageBitmap = PhotoUtils.decodeSampledBitmapFromFile(dayPhoto, realImagePath);
dbAdapter.setDayImage(realImagePath, dayOfMonth, month, year);
dayPhoto.setImageBitmap(imageBitmap); // this doesn't work, the image is not updated
}
}
答案 0 :(得分:1)
在dayPhoto.setImageBitmap(imageBitmap);
dayPhoto.invalidate();
答案 1 :(得分:1)
尝试使用setImageDrawable
,如下所示:
dayPhoto.setImageDrawable(new BitmapDrawable(imageBitmap));
答案 2 :(得分:0)
我设法解决了问题,这是在其他地方。
我需要使用onWindowsFocusChanged
方法来设置setImageBitmap,因为我无法在onCreate方法中执行此操作。
所以我的代码是:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_day);
initializeLayoutAndContent();
initializeActionBar();
}
private void initializeLayoutAndContent() {
dayPhoto = (ImageView) findViewById(R.id.dayImage);
int id = getIntent().getExtras().getInt("dayPosition");
day = dbAdapter.getAllDaysFromDb().get(id);
dayOfMonth = day.getDayId();
month = day.getMonthId();
year = day.getYearId();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
String imgPath = day.getPhotoPath();
if (imgPath != null) {
dayPhoto.setImageBitmap(PhotoUtils.decodeSampledBitmapFromFile(dayPhoto, imgPath));
}
}
我只需要将几乎整个initializeLayoutAndContent
方法移动到onWindowsFocusChanged
,以便每次使用dayPhoto初始化数据。