有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java EditText自动保存设备旋转后的值

我在Android Studio中创建了一个示例应用程序,以了解Android应用程序的生命周期。我知道方向更改会完全重新启动活动(即再次调用OnCreate方法)。 据我所知,方向改变应该会破坏上下文,并在设备旋转后显示空白文本。但是,在不重写onSaveInstanceState和onRestoreInstanceState方法的情况下,它正在保存上下文

我没有任何碎片。它只是AndroidStudio提供的基本模板,几乎没有覆盖的生命周期方法。 这是我的主要活动课:

package com.example.安卓.a2_screen_orientation_change;

import 安卓.os.Bundle;
import 安卓.support.v7.app.AppCompatActivity;
import 安卓.util.Log;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

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

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "in method onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "in method onResume");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "in method onRestart");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG, "in method onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "in method onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "in method onDestroy");
    }
}

布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    xmlns:tools="http://schemas.安卓.com/tools"
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    tools:context="com.example.安卓.a2_screen_orientation_change.MainActivity">

    <EditText
        安卓:id="@+id/editText"
        安卓:layout_width="match_parent"
        安卓:layout_height="wrap_content" />

</LinearLayout>

AbdroidManifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    package="com.example.安卓.a2_screen_orientation_change">

    <application
        安卓:allowBackup="true"
        安卓:icon="@mipmap/ic_launcher"
        安卓:label="@string/app_name"
        安卓:roundIcon="@mipmap/ic_launcher_round"
        安卓:supportsRtl="true"
        安卓:theme="@style/AppTheme">
        <activity 安卓:name=".MainActivity">
            <intent-filter>
                <action 安卓:name="安卓.intent.action.MAIN" />

                <category 安卓:name="安卓.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

图片: Text got saved even after device orientation change


共 (3) 个答案

  1. # 1 楼答案

    Android自动处理保存状态&;在显式指定

    android:configChanges="orientation"
    

    在你最重要的时刻

    如果ui元素没有id,Android将无法恢复元素的状态

    请参考这里的答案 https://stackoverflow.com/a/19234974/1099156

  2. # 2 楼答案

    因为EditText是一个焦点视图,所以在PhoneWindow中,它的状态将自动保存在saveHierarchyState()方法中。您可以看到以下代码:

    @Override
    public Bundle saveHierarchyState() {
        Bundle outState = new Bundle();
        if (mContentParent == null) {
            return outState;
        }
        SparseArray<Parcelable> states = new SparseArray<Parcelable>();
        mContentParent.saveHierarchyState(states);
        outState.putSparseParcelableArray(VIEWS_TAG, states);
        // save the focused view id
        View focusedView = mContentParent.findFocus();
        if (focusedView != null) {
            if (focusedView.getId() != View.NO_ID) {
                outState.putInt(FOCUSED_ID_TAG, focusedView.getId());
            } else {
                if (false) {
                    Log.d(TAG, "couldn't save which view has focus because the focused view "
                            + focusedView + " has no id.");
                }
            }
        }
        // save the panels
        SparseArray<Parcelable> panelStates = new SparseArray<Parcelable>();
        savePanelState(panelStates);
        if (panelStates.size() > 0) {
            outState.putSparseParcelableArray(PANELS_TAG, panelStates);
        }
        if (mActionBar != null) {
            outState.putBoolean(ACTION_BAR_TAG, mActionBar.isOverflowMenuShowing());
        }
        return outState;
    }
    

    以及TextView中的代码:

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        // Save state if we are forced to
        final boolean freezesText = getFreezesText();
        boolean hasSelection = false;
        int start = -1;
        int end = -1;
        if (mText != null) {
            start = getSelectionStart();
            end = getSelectionEnd();
            if (start >= 0 || end >= 0) {
                // Or save state if there is a selection
                hasSelection = true;
            }
        }
        if (freezesText || hasSelection) {
            SavedState ss = new SavedState(superState);
            if (freezesText) {
                if (mText instanceof Spanned) {
                    final Spannable sp = new SpannableStringBuilder(mText);
                    if (mEditor != null) {
                        removeMisspelledSpans(sp);
                        sp.removeSpan(mEditor.mSuggestionRangeSpan);
                    }
                    ss.text = sp;
                } else {
                    ss.text = mText.toString();
                }
            }
            if (hasSelection) {
                // XXX Should also save the current scroll position!
                ss.selStart = start;
                ss.selEnd = end;
            }
            if (isFocused() && start >= 0 && end >= 0) {
                ss.frozenWithFocus = true;
            }
            ss.error = getError();
            if (mEditor != null) {
                ss.editorState = mEditor.saveInstanceState();
            }
            return ss;
        }
        return superState;
    }
    

    因此,如果在xml文件中删除EditTextView的id:

        <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.android.a2_screen_orientation_change.MainActivity">
    
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    
    </LinearLayout>
    

    你会看到你想要的!(来自@Mike M的补充罐)

  3. # 3 楼答案

    默认情况下,Android正在恢复某些视图的状态。 在布局xml中,将android:saveEnabled="false"添加到编辑文本中。并且EditText的值将不会保留