Search code examples
androidandroid-fragmentsandroid-preferences

Is it possible to auto-scroll down a PreferenceFragment to a desired (settings) entry?


I'm using startActivity(new Intent(this, SettingsActivity.class)) from an Activity to call the PreferenceFragment of my app when a certain user interaction is required to be performed into the preferences. I think would be good to scroll down to reach the involved preference.

I found solutions about how to scroll views into ScrollViews and ListViews, but nothing related to PreferenceFragments.

My preferences look like:

public class SettingsActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // ...

        PreferenceManager.setDefaultValues(this, R.xml.settings, false);

        getFragmentManager().beginTransaction()
            .replace(android.R.id.content, new SettingsFragment())
            .commit();
    }

    public static class SettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener {

        //preferences:
        private Preference p
        // [...]

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.settings);

            //preference click listeners...
            p = (Preference) findPreference("PR_NAME");
            p.setOnPreferenceClickListener(new OnPreferenceClickListener() {

                public boolean onPreferenceClick(Preference preference) {
                    // ...
                    return true;
                }
            });
            // [...]
        }
    }
}

Thanks for any suggestion


Solution

  • yes, it is possible but it is hacky so nor recommended. it assumes that Preferences are backed by a ListView with id == android.R.id.list, so when you have reference to that ListView you can call setSelection(position)