簡體   English   中英

退出應用后保存ImageView狀態(onSaveInstanceState)

[英]Save a ImageView state after exit App (onSaveInstanceState)

我有一個應用程序,允許用戶從圖庫中選擇圖片,並將其用作個人資料圖片,選擇圖片並在我的應用程序中設置為“ ImageView”。

問題是,當應用程序關閉時,如果活動被更改,則顯示圖片消失,或者再次返回默認圖片,我想保存此圖片狀態,以便返回活動狀態或關閉並重新打開應用程序時,圖片繼續在那里並不需要重新設置。 我是開發中的新手,如果您能幫助我在下面查看我的代碼並進行必要的更改並給我准備好的代碼,我將非常感謝,因為我花了幾天時間這樣做,但我仍然不能。 我需要准備好的代碼,因為我是開發新手,如果您嘗試解釋一些我不會理解的內容。

這是我選擇圖片的代碼:

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();
    }

}

}

嘗試覆蓋onSaveInstanceStateActivity生命周期方法。 這是有關最佳做法的博客文章。 http://inthecheesefactory.com/blog/fragment-state-saving-best-practices/en

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM