Search code examples
androidandroid-preferences

android - changing ListPreference value from an Activity


Following the new API's I have created a pretty simple PreferenceFragment:

  public class PrefsFragment extends PreferenceFragment {

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    addPreferencesFromResource(R.xml.preferences);
}

    }

I use that in my Activity created to enable the user to change app settings:

  public class SetPreferenceActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

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

}

   }

Now I need to change the summary of a ListPreference according to user's choice. There is no findPreference() method defined for Activity class, so how can I access the desired preference?

Sorry if the answer is obvious, I'm not really familiar with the new API and always used a PreferenceActivity before it became deprecated..


Solution

  • Instead of doing new PrefsFragment() right in your statement where you replace the fragment you can do this.

    PreferenceFragment pFrag = new PrefsFragment();
    PrefsFragment pf = (PrefsFragment)pFrag;
    
    getFragmentManager().beginTransaction()
            .replace(android.R.id.content, pFrag).commit();
    

    then in your PreferenceFragment you create a public method that you can change what you want

    pf.changeMyPreference();