简体   繁体   中英

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..

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM