Search code examples
androidandroid-edittextfragmentandroid-lifecycleandroid-orientation

Why does my EditText not save its State (mostly its Text)?


So EditTexts should save their Text when changing orientation. In this particular Fragment, they dont. Why is that?

my Fragment:

 public class LoginFragment extends Fragment {

    /**
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater,
     *      android.view.ViewGroup, android.os.Bundle)
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    return inflater.inflate(R.layout.login, container, false);

    }

    /**
     * 
     * @see android.support.v4.app.Fragment#onStart()
     */
    @Override
    public void onStart() {
    super.onStart();

    getView().findViewById(R.id.login_ok).setOnClickListener(
        new OnClickListener() {

            public void onClick(View v) {
            startActivity(new Intent(getActivity(),
                StartActivity.class));
            }
        });
    }
}

My edittexts in xml:

 <EditText
        android:id="@+id/login_user"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:background="@drawable/roundedcorner"
        android:ems="10"

        android:hint="@string/email"
        android:inputType="textEmailAddress"
        android:padding="8dp" >

        <requestFocus />
    </EditText>





    <EditText
        android:id="@+id/login_pw"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:background="@drawable/roundedcorner"
        android:ems="10"

        android:hint="@string/password"
        android:inputType="textPassword"
        android:padding="8dp" />

This is the onCreate Method of my Activity:

super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_login);
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.add(R.id.login_frame, new LoginFragment());
ft.commit();`

Solution

  • Okay so I had this problem, because i added my Fragment with a FragmentTransaction into a FrameLayout(which had a unique ID).

    Now I've declared my Fragment once again in the XML with a unique ID and it works.

    I cant really explain why it wont work when adding it with a FragmentTransaction, if the container has an unique ID, but atleast it works now.