【问题标题】:Android - Fragment using NavigationDrawer and onSavedInstanceStateAndroid - 使用 NavigationDrawer 和 onSavedInstanceState 的片段
【发布时间】:2013-12-20 00:31:03
【问题描述】:

我正在关注this 创建一个抽屉式导航。 在我的一个片段中,我有一个 EditText。 如果我旋转屏幕,我希望 EditText 上的文本不会改变。

我尝试使用Bundle savedInstanceState,但它不起作用。 我认为我应该从我的 Manifest 中删除 android:configChanges 行,但我没有那行。

我尝试了this question 的正确答案,但它仍然不适合我。 所以我该怎么做?谢谢:)

【问题讨论】:

    标签: android android-fragments bundle navigation-drawer


    【解决方案1】:

    如果您没有 android:configChanges 行,那么 Android 将处理屏幕旋转。您的应用程序将被销毁并重新创建。在应用程序被销毁之前,Android 会调用 onSavedInstanceState,您可以在其中保存数据以供娱乐使用。重新创建应用时,传递给 onCreate 的包不为空,并且包含您保存的状态。

    试试

    public void onSavedInstanceState(Bundle bundle) {
        bundle.put("editTextString",et.getText().toString());
        super.onSavedInstanceState(bundle);
    }
    

    public void onCreate(Bundle savedInstanceState) {
        if(savedInstanceState!=null) {
             String savedText = savedInstanceState.get("editTextString");
             et.setText(savedText);
        }
    } 
    

    【讨论】:

    • 如果我按照你说的那样尝试,我会收到“方法 onSavedInstanceState(Bundle) 未定义片段类型”错误。如果我更改为 super.onSaveInstanceState(bundle);它仍然不起作用,我之前已经尝试过:(
    猜你喜欢
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多