处理屏幕旋转而不会丢失数据 - Android

Ric*_*eri 41 android android-intent android-layout

我正在疯狂地弄清楚处理屏幕旋转的最佳方法是什么.我在这里阅读了数百个问题/答案,但我真的很困惑.

如何在重新创建活动之前保存myClass数据,这样我可以保留所有内容以重绘活动而无需另外无用的初始化?

有没有比parcelable更清洁,更好的方法?

我需要处理旋转,因为我想在横向模式下更改布局.

public class MtgoLifecounterActivity extends Activity {

    MyClass myClass;

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

        If ( ?? first run...myClass == null ? ) {
            myClass = new MyClass();
        } else {
            // do other stuff but I need myClass istance with all values.
        }
        // I want that this is called only first time. 
        // then in case of rotation of screen, i want to restore the other instance of myClass which
        // is full of data.
    }
Run Code Online (Sandbox Code Playgroud)

Coo*_*ol7 44

在Manifest的Activity Tag中你应该提到

<activity
        android:name="com.example.ListActivity"
        android:label="@string/app_name" 
        android:configChanges="keyboardHidden|orientation">
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Android 2.3(API级别13)及以上版本

<activity
        android:name="com.example.Activity"
        android:label="@string/app_name" 
        android:configChanges="keyboardHidden|orientation|screenSize">
Run Code Online (Sandbox Code Playgroud)

它应该必须工作.

它仅适用于活动标记,而不适用于应用程序标记

  • 我的问题出在screenSize属性中,感谢Prashant (3认同)

Moh*_*ikh 27

可以使用覆盖方法onSaveInstanceState()onRestoreInstanceState().或者要停止调用onCreate()屏幕旋转,只需在清单xml中添加此行android:configChanges="keyboardHidden|orientation"

注意:您的自定义类必须实现Parcelable以下示例.

@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable("obj", myClass);
    }

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
 // TODO Auto-generated method stub
 super.onRestoreInstanceState(savedInstanceState);
 myClass=savedInstanceState.getParcelable("obj"));
}

public class MyParcelable implements Parcelable {
     private int mData;

 public int describeContents() {
     return 0;
 }

 /** save object in parcel */
 public void writeToParcel(Parcel out, int flags) {
     out.writeInt(mData);
 }

 public static final Parcelable.Creator<MyParcelable> CREATOR
         = new Parcelable.Creator<MyParcelable>() {
     public MyParcelable createFromParcel(Parcel in) {
         return new MyParcelable(in);
     }

     public MyParcelable[] newArray(int size) {
         return new MyParcelable[size];
     }
 };

 /** recreate object from parcel */
 private MyParcelable(Parcel in) {
     mData = in.readInt();
 }


}
Run Code Online (Sandbox Code Playgroud)


小智 16

可能已经解决了这个问题,但只是对于坚持使用它的新成员进行了一次小更新,只需查看Google Developer Site,从API级别13开始,您只需要将此代码添加到Manifest:

<activity android:name=".SplashScreensActivity"
          android:configChanges="orientation|keyboardHidden|screenSize"
          android:label="@string/app_name">
Run Code Online (Sandbox Code Playgroud)

当其中一个配置发生更改时,SplashScreensActivity不会重新启动.相反,SplashScreensActivity接收对onConfigurationChanged()的调用.此方法传递一个Configuration对象,该对象指定新设备配置.通过读取"配置"中的字段,您可以确定新配置并通过更新界面中使用的资源进行适当的更改.在调用此方法时,将更新活动的Resources对象以根据新配置返回资源,这样您就可以轻松重置UI的元素,而无需系统重新启动您的活动.


dev*_*jay 14

这里的问题是你正在失去App的"状态".在OOP中,什么是国家?变量!究竟!因此,当您丢失变量的数据时.

现在这里是你能做的,找出失去状态的变量.

在此输入图像描述

当您旋转设备时,您的当前活动将被完全销毁,即通过onSaveInstanceState() onPause() onStop() onDestroy() 并完全创建一个新的活动,该活动将通过onCreate() onStart() onRestoreInstanceState.

粗体中的两个方法onSaveInstanceState()保存将要销毁的当前活动的实例.onRestoreInstanceState此方法恢复上一个活动的已保存状态.这样您就不会丢失以前的应用状态.

以下是您使用这些方法的方法.

 @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);

        outState.putString("theWord", theWord); // Saving the Variable theWord
        outState.putStringArrayList("fiveDefns", fiveDefns); // Saving the ArrayList fiveDefns
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onRestoreInstanceState(savedInstanceState, persistentState);

        theWord = savedInstanceState.getString("theWord"); // Restoring theWord
        fiveDefns = savedInstanceState.getStringArrayList("fiveDefns"); //Restoring fiveDefns
    }
Run Code Online (Sandbox Code Playgroud)

编辑:更好的方法:上述维护数据的方法不是维护生产代码/应用程序中数据的最佳方法.Google IO 2017引入了ViewModel来保护您的数据免受配置更改(如屏幕旋转).使用变量将所有数据保存在活动中并不是一个好的软件设计,违反了单一责任原则,因此使用ViewModel将您的数据存储与活动分开.

  • ViewModel将负责显示的数据.
  • Activity将负责如何显示数据.
  • 如果存储数据的复杂性增加,请使用其他存储库类.

这只是分离课程和他们的责任的一种方式,这将在制作结构良好的应用程序时有很长的路要走.

  • 比接受的答案要好得多,谢谢! (2认同)

Bob*_*ke4 5

如果您不需要重新启动您的活动,只需将 AndroidManifest.xml 中您的活动的 configChanges 属性设置为:

    android:configChanges="keyboard|keyboardHidden|orientation"
Run Code Online (Sandbox Code Playgroud)

这将告诉操作系统您将负责处理轮换并且不会重新启动您的活动。使用此方法将使您无需保存任何类型的状态。


dmo*_*mon 5

有两种(好的)方法可以解决这个问题。让您的类实现 Parcelable 并将其放入 中的包中onSaveInstanceState(),或者,如果它更复杂(例如 AsyncTask),则将其返回到 中onRetainNonConfigurationInstance()

还有一种懒惰的方法,您可以停止对配置更改做出反应。