Handling orientation changes with Fragments

后端 未结 3 962
别那么骄傲
别那么骄傲 2020-12-19 18:11

I\'m currently testing my app with a multipane Fragment-ised view using the HC compatibility package, and having a lot of difficultly handling orientation chang

3条回答
  •  遥遥无期
    2020-12-19 18:33

    Create new Instance only for First Time.

    This does the trick:
    Create a new Instance of Fragment when the activity start for the first time else reuse the old fragment.
    How can you do this?
    FragmentManager is the key

    Here is the code snippet:

    if(savedInstanceState==null) {
        userFragment = UserNameFragment.newInstance();
        fragmentManager.beginTransaction().add(R.id.profile, userFragment, "TAG").commit();
    }
    else {
        userFragment = fragmentManager.findFragmentByTag("TAG");
    }
    

    Save data on the fragment side

    If your fragment has EditText, TextViews or any other class variables which you want to save while orientation change. Save it onSaveInstanceState() and Retrieve them in onCreateView() method

    Here is the code snippet:

    // Saving State
    
    @Override
    public void onSaveInstanceState(Bundle outState) {
         super.onSaveInstanceState(outState);
         outState.putString("USER_NAME", username.getText().toString());
         outState.putString("PASSWORD", password.getText().toString());
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
    
         View view = inflater.inflate(R.layout.user_name_fragment, parent, false);
    
         username = (EditText) view.findViewById(R.id.username);
         password = (EditText) view.findViewById(R.id.password);
    
    
         // Retriving value
    
         if (savedInstanceState != null) {
             username.setText(savedInstanceState.getString("USER_NAME"));
             password.setText(savedInstanceState.getString("PASSWORD"));
         }
    
         return view;
    }
    

    You can see the full working code HERE

提交回复
热议问题