Home » Android » android – Delete current preference screen and go back to main preference screen

android – Delete current preference screen and go back to main preference screen

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a PreferenceActivity launched where I add some preference screens programmatically. So I have a list with my preference screens.

Example:

  • Toto
  • Titi
  • Tata

So I iterate and call a function (Board is a custom object):

private PreferenceScreen CreatePreferenceScreen(Board b) {
    PreferenceScreen p = getPreferenceManager().createPreferenceScreen(this);
    p.setPersistent(true);
    p.setKey("preferenceScreen_" + b.getId());

    PreferenceCategory general = new PreferenceCategory(this);
    general.setTitle("General");
    p.addPreference(general);

    Preference delete = new Preference(this);
    delete.setTitle("delete");
    final PreferenceScreen pFinal = p;
    delete.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            String delId = board.getId();
            PreferenceCategory themes = (PreferenceCategory) findPreference("themes");
            PreferenceScreen screen =(PreferenceScreen)findPreference("preferenceScreen_" + delId); 
            themes.removePreference(screen);
            /*GO BACK TO PREFERENCEACTIVITY HERE OR KILL THIS SCREEN*/
            return true;
        }
    });
    general.addPreference(delete);
    return p;
}

If I click on toto, it opens the preference screen of toto and on this screen I have an option “Delete”. If I click on delete it removes this preference screen from the PreferenceActivity (the previous screen) but I’m still on the preference screen toto.

I’d like to go back to the previous screen when I use “Delete”.

I can’t use finish() on my preference screen toto because it exits the app.
If I click on my back button, I go back to the PreferenceActivity (previous screen) and my toto preferences screen has been removed (yata, that function worked!)

How to&Answers:

The user found the solution thanks to the PreferenceScreen developer documents.

When it appears inside another preference hierarchy, it is shown and serves as the gateway to another screen of preferences (either by
showing another screen of preferences as a Dialog or via a
startActivity(android.content.Intent) from the getIntent()). The
children of this PreferenceScreen are NOT shown in the screen that
this PreferenceScreen is shown in. Instead, a separate screen will be
shown when this preference is clicked.

So replace this:

/*GO BACK TO PREFERENCEACTIVITY HERE OR KILL THIS SCREEN*/

with this:

pFinal.getDialog().dismiss();

And it accomplishes the desired job: close the current preferenceScreen.