简体   繁体   中英

How to update listpreference summary (findPreference() does not work)?

So, SettingsActivity implements a SettingsFragment. I am following Udacity course. My main problem is, findPreference() does not work! Here's what it says on developer.android.com site:

findPreference Added in API level 1 Preference findPreference (CharSequence key) This method was deprecated in API level 11. This function is not relevant for a modern fragment-based PreferenceActivity.

So, how do I bring in listPreference for a FRAGMENT? If I use PreferenceActivity, then this method works but it is deprecated.

package com.example.android.listview1;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.preference.*;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ListPopupWindow;

import java.util.prefs.PreferenceChangeListener;



public class SettingsActivity extends AppCompatActivity implements     Preference.OnPreferenceChangeListener {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getFragmentManager().beginTransaction().replace(android.R.id.content,new SettingsFragment()).commit();

    **bindPreferenceSummaryToValue(findPreference());**


}
private void bindPreferenceSummaryToValue(Preference preference)
{
 preference.setOnPreferenceChangeListener(this);
onPreferenceChange(preference,PreferenceManager.getDefaultSharedPreferences(preference.getContext()).getString(preference.getKey(),"") );
}

    @Override
    public boolean onPreferenceChange(Preference preference, Object     newValue)    {

  String value = newValue.toString();

    //if the preference is an instance of ListPreference then you convert the preference object to ListPreference

    if(preference instanceof ListPreference) {
        ListPreference listPreference = (ListPreference) preference;
        //return the index of the value that is selected
        int prefIndex = listPreference.findIndexOfValue(value);

        //if there's at least 1 item in the ListPreference, then you set the summary by getting the object at the index

        if (prefIndex >= 0) {
            preference.setSummary(listPreference.getEntries()[prefIndex]);
        }

        else
            preference.setSummary(value);
    }
    return true;
}

}

I figured out how to solve the issue. Move all the code/methods except for onCreate to SettingsFragment. Move bindPreferenceSummaryToValue(findPreference()) to SettingsFragment as well and get rid of the implementation from onCreate().

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