How can I handle orientation changes so that the Fragment does not load?

When the EditText line in the user interface receives focus, DatePickerFragment starts the date entry for the user.

When changing the orientation, if the EditText line has focus and the previously entered date (so that length() > 0 ), I don’t want the fragment to be shown automatically.

Is there a way to change or add code so that if the activity has been re-created and the EditText line is focused, it will not automatically launch DatePickerFragment ?

Would it be nice to do something in onResume() ?

Or do something with savedInstanceState() and !=null ?

 public class Activity extends AppCompatActivity { ... EditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { ... if (hasFocus && (EditText.getText().length() == 0)) { DatePickerFragment newFragment = new DatePickerFragment(); newFragment.show(getSupportFragmentManager(), "datePicker"); } else if (hasFocus && (EditText.getText().length() > 0)) { ... DatePickerFragment newFragment = new DatePickerFragment(); newFragment.show(getSupportFragmentManager(), "datePicker"); } } }); } 
+5
source share
2 answers

Are you using viewPager or just adding a snippet to your activity? One way is to save the data that you want to support when turning into the onSaveInstanceState(Bundle outState) , and then restore that data inside onCreate using

  if(savedInstanceState != null) { //get your data } 

or just add your fragment only if the activity has been downloaded (does not restart after the device is rotated)

 if(savedInstanceState == null) { mFragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction(); YourFragment fragment = new YourFragment(); fragmentTransaction.add(R.id.fragment_container, fragment); fragmentTransaction.commit(); } 

In any case, you definitely need to check this and this , they can be useful.

+4
source

If I were you, instead of using OnFocusChangeListener I would use OnClickListener to show the fragment whenever EditText clicked and EditText not focused.

To change the orientation, it is worth noting that you can prevent configuration changes that affect activity by adding android:configChanges="orientation" in the manifest to the associated activity. Not sure if this will help in your case, but you can take a look.

+3
source

Source: https://habr.com/ru/post/1232773/


All Articles