我是Android编程的新手,并且一直在尝试构建应用程序.在我的新应用程序中,我让用户按下一个按钮,允许他们在他们的设备上选择一个应用程序,如"图库",以便选择图像.然后,该图像显示在活动屏幕上的图像视图窗口中.不幸的是,当我转动手机并改变方向时,图像会丢失,他们必须再次选择它.
如何保存位图图像并在方向更改后重新显示?
这是我用来让用户选择图像应用程序,选择图像,并在图像视图窗口中显示图像的代码函数.
@Override
protected void onActivityResult( int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
Uri targetUri = data.getData();
textTargetUri.setText(targetUri.toString());
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
targetImage.setImageBitmap(bitmap);
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
上面的函数在我的onCreate中初始化,以响应此代码中显示的按钮单击:
Button buttonLoadImage = (Button)findViewById(R.id.loadimage);
textTargetUri = (TextView)findViewById(R.id.targeturi);
targetImage = (ImageView)findViewById(R.id.targetimage);
buttonLoadImage.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}});
Run Code Online (Sandbox Code Playgroud)
基本上,我只需要将这个布尔值放在我的onCreate中并让它将图像放回窗口中.它还显示文本,显示图像在设备上的位置,但这对我来说并不像能够让图像保留在屏幕上一样重要.
if (savedInstanceState != null) {
}
Run Code Online (Sandbox Code Playgroud)
但它似乎在方向改变后擦除了数据?我不知道如何保存数据并将其恢复为在该布尔值内使用.我感谢您提供的任何建议,代码或链接!
更新:
感谢Vishal …