How to retain EditText data on orientation change?

后端 未结 12 1956
暗喜
暗喜 2020-12-05 13:34

I have a Login screen which consists of 2 EditTexts for Username and Password. My requirement is that on orientation change , input data(if any) in EditText should r

12条回答
  •  一个人的身影
    2020-12-05 14:20

    A better approach is to let android handle the orientation change. Android will automatically fetch the layout from the correct folder and display it on the screen. All you need to do is to save the input values of the edit texts in the onSaveInsanceState() method and use these saved values to initialize the edit texts in the onCreate() method.
    Here is how you can achieve this:

    @Override
    protected void onCreate (Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_screen);
        ...
        ...
        String userName, password;
        if(savedInstanceState!=null)
        {
            userName = savedInstanceState.getString("user_name");
            password= savedInstanceState.getString("password");
        }
    
        if(userName != null)
            userNameEdtTxt.setText(userName);
        if(password != null)
            passEdtTxt.setText(password);
    }
    

    >

    @Override
        protected void onSaveInstanceState (Bundle outState)
        {
            outState.putString("user_name", userNameEdtTxt.getText().toString());
            outState.putString("password",  passEdtTxt.getText().toString());
        }
    

提交回复
热议问题