退出App(onSaveInstanceState)后保存ImageView状态

时间:2016-01-28 22:11:42

标签: android image imageview

我有一个应用程序,我允许用户从galery中选择一张图片,它用作PROFILE PICTURE,选择一张图片并设置在" ImageView"在我的应用程序中。

问题是,当应用程序关闭时,如果活动被更改为图片desapear,或者再次返回默认图片,我想保存此图片状态,以便在返回活动时或关闭并重新打开应用程序时图片继续那里,不需要重新设置。 我是开发新手,如果你能帮助我查看下面的代码,并做出必要的修改并给我准备好的代码,我将非常感激,因为我花了好几天时间去做,但我还是不能。我需要一个准备好的代码,因为我是开发新手,如果你尝试解释我不理解的东西。

以下是我选择图片的代码:

public class MainActivity extends Activity {
private static int RESULT_LOAD_IMG = 1;
String imgDecodableString;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void loadImagefromGallery(View view) {
    // Create intent to Open Image applications like Gallery, Google Photos
    Intent galleryIntent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    // Start the Intent
    startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        // When an Image is picked
        if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                && null != data) {
            // Get the Image from data

            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            // Get the cursor
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            // Move to first row
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            imgDecodableString = cursor.getString(columnIndex);
            cursor.close();
            ImageView imgView = (ImageView) findViewById(R.id.imgView);
            // Set the Image in ImageView after decoding the String
            imgView.setImageBitmap(BitmapFactory
                    .decodeFile(imgDecodableString));

        } else {
            Toast.makeText(this, "You haven't picked Image",
                    Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                .show();
    }

}

}

1 个答案:

答案 0 :(得分:0)

尝试重写onSaveInstanceState Activity生命周期方法。这是一篇关于其最佳实践的博客文章。 http://inthecheesefactory.com/blog/fragment-state-saving-best-practices/en

相关问题