Search code examples
androidpreferenceactivity

Programatically close PreferenceScreen and its PreferenceActivity


Here is the case:

  1. From my MainActivity I open the PreferenceActivity of my app;
  2. In PreferenceActivity I have two PreferenceScreens and also a MenuItemwith an icon to start another Activity for result. If I enter in any of the PreferenceScreens the icon is still visible so I also can start the new Activity from the current PreferenceScreen that I am in.

  3. Case 1. If I start the new Activity directly from the PreferenceActivity without entering in any of its child screen, it does its job, returns a result and I am back to the parent PreferenceActivity. I determine if I am in the PreferenceActivity and call finish() method and return to my MainActivity- job done!

  4. Case 2. I enter in a child PreferenceScreen, press the MenuItem icon, start the new Activity, it does its job, returns me a result and I am back to the child screen. I determine If I am in a PreferenceScreen and call finish(). The child screen is closed but unlike Case 1, I am back to my parent PreferenceActivity. How to close the parent and return to my MainActivity?

Solution

  • I figured it out.... My PreferenceActivity has two PreferenceScreens. So to open any of it I use screenPreference.setOnPreferenceClickListener(). In that listener I just call PreferenceActivity.this.finish(). The parent is closed and the child is opened. Already in the PreferenceScreen child, I am in Case 2 so when I call PreferenceActivity.finish(), the child screen is closed, parent also and I am directly navigated to my MainActivity. :)