OnPreferenceChangeListener不会被调用

时间:2014-03-20 03:41:06

标签: android sharedpreferences listener

我想在单击另一个ListPreference中的项目时更改EditTextPreference的值。但OnPreferenceChangeListener永远不会被调用。

继承我的代码:

public class FragmentPreferences extends PreferenceActivity {

  /*@Override
  public void onBuildHeaders(List<Header> target) {
    loadHeadersFromResource(R.xml.preference_headers, target);
  }*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Display the fragment as the main content.
        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new UserPreferenceFragment())
                .commit();
        addPreferencesFromResource(R.xml.userpreferences);
        ListPreference listPreference = (ListPreference) findPreference("PREF_MEASURE_UNITS");
        if(listPreference.getValue()==null) {
            // to ensure we don't get a null value
            // set first value by default
            listPreference.setValueIndex(0);
        }
        //listPreference.setSummary(listPreference.getValue().toString());
        listPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                //preference.setSummary(newValue.toString());
                EditTextPreference EditTextPreference = (EditTextPreference) findPreference("PREF_CAMERA_HEIGHT");
                if (newValue.equals(0))
                {

                    EditTextPreference.setText(String.format("%.1f",Float.valueOf(EditTextPreference.getText().replace(',','.'))*2.54f));
                }
                else if (newValue.equals(1))

                    EditTextPreference.setText(String.format("%.1f",Float.valueOf(EditTextPreference.getText().replace(',','.'))/2.54f));
                return true;
            }
        });
    }

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。

我必须将代码放在

下面
getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new UserPreferenceFragment())
                .commit();

在班级

public  class UserPreferenceFragment extends PreferenceFragment{

现在正在运作