Toolbar title changes on rotation on device to ent

2019-09-09 11:21发布

问题:

I have an editText directly under my Toolbar. But when my device rotates, the Toolbar's title, (set by XML) changes to the editText's current text.

    <android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/colorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/newOccasion"
        android:textColor="#FFFFFF"
        android:textSize="18sp" />
</android.support.v7.widget.Toolbar>

<EditText
    android:id="@+id/titleET"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="20dp"
    android:drawableStart="@drawable/ic_title"
    android:hint="@string/titleET"
    android:maxLines="1"
    android:nextFocusLeft="@+id/titleET"
    android:nextFocusUp="@+id/titleET"
    android:paddingEnd="5dp"
    android:paddingStart="5dp"
    android:textSize="17sp"
    android:theme="@style/inputColors"
    android:lines="1"
    android:maxLength="35"/>

FULL XML HERE: http://pastebin.com/JBeAkVqY

回答1:

Just Override these methods in your activity:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    //do nothing
}

It worked perfectly. These restore your previous texts to the way they were when you do something such as rotating your device.