How to retain EditText data on orientation change?

后端 未结 12 1963
暗喜
暗喜 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:01

    As pointed out by Yalla T it is important to not recreate the fragment. The EditText will not lose its content if the existing fragment is reused.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setContentView(R.layout.activity_frame);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
        // Display the fragment as the main content.
        // Do not do this. It will recreate the fragment on orientation change!
        // getSupportFragmentManager().beginTransaction().replace(android.R.id.content, new Fragment_Places()).commit();
    
        // Instead do this
        String fragTag = "fragUniqueName";
        FragmentManager fm = getSupportFragmentManager();
        Fragment fragment = (Fragment) fm.findFragmentByTag(fragTag);
        if (fragment == null)
            fragment = new Fragment_XXX(); // Here your fragment
        FragmentTransaction ft = fm.beginTransaction();
        // ft.setCustomAnimations(R.xml.anim_slide_in_from_right, R.xml.anim_slide_out_left,
        // R.xml.anim_slide_in_from_left, R.xml.anim_slide_out_right);
        ft.replace(android.R.id.content, fragment, fragTag);
        // ft.addToBackStack(null); // Depends on what you want to do with your back button
        ft.commit();
    
    }
    

提交回复
热议问题