Search code examples
androidandroid-activitypreferenceactivitypreferencescreenandroid-settings

Open a Sub-Preference Screen of SettingsActivity on button click


My SettingsActivity has sub-preference screens. I want to directly open one of the nested PreferenceScreen in SettingsActivity from another Activity on button click.

Basically, I want the user to be redirected from an Activity to the sub-section of theSettingsActivity screen. Is there a way to do it?

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory
        android:title="@string/pref_header_general">
    </PreferenceCategory>
    <ListPreference
    ..
    />
    <PreferenceScreen <!--Show this sub preference screen in Setttings on button click -->

        android:key="@string/pref_key_open_this_screen"
        android:summary="@string/pref_summary_sample"
        android:title="@string/pref_title_sample" >
        <SwitchPreference
            android:defaultValue="@string/pref_summary_enabled"
            android:key="@string/pref_key_enabled"
            android:title="@string/pref_title_enabled"
            android:summary="@string/pref_summary_reminder_enabled"/>
        <ListPreference
        ..
        />
        <ListPreference
        ..
        />
    </PreferenceScreen>
</PreferenceScreen>

Solution

  • I found a solution after some research. Hope it helps somebody else. We can use the code below to simulate click on a sub-preference screen.

    • Start an intent to SettingsActivity from the activity of your choice.
    • Pass an extra to let the SettingsActivity know that it needs to open the sub-preference screen
    • IfSettingsActivity receives the intent, run the following code and it will open the sub-preference screen

    Code :

    PreferenceScreen preferenceScreen  = (PreferenceScreen) findPreference(getResources().getString(R.string.pref_key_root_screen));
    PreferenceScreen subPreferenceScreen  = (PreferenceScreen) findPreference(getResources().getString(R.string.pref_key_sub_preference_screen));
    final ListAdapter listAdapter = preferenceScreen.getRootAdapter();
    final int itemsCount = listAdapter.getCount();
    int itemNumber;
    for (itemNumber = 0; itemNumber < itemsCount; ++itemNumber) {
        if (listAdapter.getItem(itemNumber).equals(subPreferenceScreen)) {
            //simulates click on the sub-preference
            preferenceScreen.onItemClick(null, null, itemNumber, 0);
            break;
        }
    }