Android 保存数据并更改方向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12214600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 10:02:43  来源:igfitidea点击:

Save data and change orientation

androidorientation

提问by Max Usanin

I have two activities and I use android:configChanges="keyboardHidden|orientation|screenSize"

我有两个活动,我使用 android:configChanges="keyboardHidden|orientation|screenSize"

 @Override
      public void onConfigurationChanged(Configuration newConfig) {
          super.onConfigurationChanged(newConfig);
        setContentView(R.layout.activity_main);
          if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {

          } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {

          }
      }

One active use for portrait to landscape orientation of the second but when the orientation changes, activity is loaded and data is lost

一个主动使用纵向到横向的第二个 但是当方向改变时,活动被加载并且数据丢失

How can I save the data and change the activity orientation?

如何保存数据并更改活动方向?

回答by Daud Arfin

If you have small data, you can save and restore it using onSavedInstanceStateand onRestoreInstanceState.. for details go through this link Saving data

如果您有小数据,您可以使用onSavedInstanceStateonRestoreInstanceState..保存和恢复它的详细信息,请访问此链接保存数据

But in case, you have large data then I must say, you should not allow for the orientation changes(which force your activity to recreate). You can restrict it by adding below line in manifest file :

但是,如果您有大量数据,那么我必须说,您不应该允许方向更改(这会迫使您的活动重新创建)。您可以通过在清单文件中添加以下行来限制它:

android:configChanges="orientation|keyboardHidden" // fixes orientation

回答by sdabet

See onSaveInstanceState(Bundle)and onRestoreInstanceState(Bundle)

查看onSaveInstanceState(Bundle)onRestoreInstanceState(Bundle)

回答by user541747

I recommend this post

我推荐这个帖子

http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html

http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html

to anyone who is still looking for a solution to this problem. The author describes how to use a Fragmentto retain data.

对于仍在寻找解决此问题的方法的任何人。作者描述了如何使用Fragment来保留数据。

Make sure to have the call

确保接到电话

setRetainInstance(true);

in the onCreate()method of your Fragment!

onCreate()你的 Fragment的方法中!

回答by Hardik Nadiyapara

you should check sample application "Multiresolution" here below you can see the snippet of code of "Multiresolution"

您应该在下面查看示例应用程序“多分辨率”,您可以看到“多分辨率”的代码片段

public final class MultiRes extends Activity {

    private int mCurrentPhotoIndex = 0;
    private int[] mPhotoIds = new int[] { R.drawable.sample_0,
            R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3,
            R.drawable.sample_4, R.drawable.sample_5, R.drawable.sample_6,
            R.drawable.sample_7 };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        showPhoto(mCurrentPhotoIndex);

        // Handle clicks on the 'Next' button.
        Button nextButton = (Button) findViewById(R.id.next_button);
        nextButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mCurrentPhotoIndex = (mCurrentPhotoIndex + 1)
                        % mPhotoIds.length;
                showPhoto(mCurrentPhotoIndex);
            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("photo_index", mCurrentPhotoIndex);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        mCurrentPhotoIndex = savedInstanceState.getInt("photo_index");
        showPhoto(mCurrentPhotoIndex);
        super.onRestoreInstanceState(savedInstanceState);
    }

    private void showPhoto(int photoIndex) {
        ImageView imageView = (ImageView) findViewById(R.id.image_view);
        imageView.setImageResource(mPhotoIds[photoIndex]);

        TextView statusText = (TextView) findViewById(R.id.status_text);
        statusText.setText(String.format("%d/%d", photoIndex + 1,
                mPhotoIds.length));
    }
}

回答by Yalla T.

You can save any Object by Overriding public Object onRetainNonConfigurationInstance ()and calling getLastNonConfigurationInstance()in your onCreate method.

您可以通过覆盖公共对象 onRetainNonConfigurationInstance ()并调用getLastNonConfigurationInstance()您的 onCreate 方法来保存任何对象。

@Override
    public Object onRetainNonConfigurationInstance() {


    return data;
    }


 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

         data = getLastNonConfigurationInstance();
    }

but if you do this, you have to change your manifest and code, so the normal process for a configuartion change is used.

但是如果你这样做,你必须改变你的清单和代码,所以使用配置更改的正常过程。

Different from the SavedInstance method, this only saves the object if the activity is killed because of a configuaration change

与 SavedInstance 方法不同,这仅在活动因配置更改而被终止时保存对象

回答by harshit

The method is onSaveInstanceState()and the system calls it when the user is leaving your activity. When the system calls this method, it passes the Bundleobject that will be saved in the event that your activity is destroyed unexpectedly so you can add additional information to it. Then if the system must recreate the activity instance after it was destroyed, it passes the same Bundleobject to your activity's onRestoreInstanceState()method and also to your onCreate()method.

该方法是onSaveInstanceState(),系统在用户离开您的活动时调用它。当系统调用此方法时,它会传递Bundle将在您的 Activity 意外销毁时保存的对象,以便您可以向其添加其他信息。然后,如果系统在销毁活动实例后必须重新创建它,它会将相同的Bundle对象传递给您的活动onRestoreInstanceState()方法以及您的onCreate()方法。

refer to http://developer.android.com/training/basics/activity-lifecycle/recreating.html

参考http://developer.android.com/training/basics/activity-lifecycle/recreating.html