0

我希望能夠在摘要字段中顯示EditTextPreference的值。具體來說,我想在PreferenceFragmentCompat中執行此操作。在摘要中顯示EditTextPreference當前值

import android.support.v7.preference.PreferenceFragmentCompat; 

public class SettingsFragment extends PreferenceFragmentCompat { 

    @Override 
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { 
     addPreferencesFromResource(R.xml.preferences); 
    } 
} 

偏好文件是這樣的:

<?xml version="1.0" encoding="utf-8"?> 
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> 
    <EditTextPreference 
     android:defaultValue="DEVICE01" 
     android:key="device_id" 
     android:title="Device ID" /> 
</PreferenceScreen> 

我見過其他的解決方案,但沒有人包括瞭如何在PreferenceFragmentCompat做到這一點。

回答

1

我認爲,它的方式是在每一個簡單PreferenceFragment相同: 在XML文件:

android:summary="@string/your_string_resource" 

在代碼:

EditTextPreference editTextPreference = (EditTextPreference) findPreference(YOUR_PREFERENCE_KEY); 
    editTextPreference.setSummary(sharedPreferences.getString(YOUR_PREFERENCE_KEY, defaultValue)); 
    editTextPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { 
     @Override 
     public boolean onPreferenceChange(Preference preference, Object o) { 

      String yourString = o.toString(); 
      sharedPreferences.edit().putString(YOUR_PREFERENCE_KEY, yourString).apply(); 
      editTextPreference.setSummary(yourString); 

      return true; 
     } 
    }); 
0

從@ grabarz121回答讓我在正確的方向。這是我加入的喜好:

android:summary="@string/pref_device_id_summary" 

這是我修改/添加到SettingsFragment類:

public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { 
    addPreferencesFromResource(R.xml.preferences); 
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext()); 
    setDeviceIdSummary(); 
} 

public void setDeviceIdSummary() { 
    final String deviceIdKey = getString(R.string.pref_device_id_key); 
    String deviceIdDefault = getString(R.string.pref_device_id_default); 
    String deviceIdValue = sharedPreferences.getString(deviceIdKey, deviceIdDefault); 

    final EditTextPreference editTextPreference = (EditTextPreference) findPreference(deviceIdKey); 
    editTextPreference.setSummary(deviceIdValue); 

    editTextPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { 
     @Override 
     public boolean onPreferenceChange(Preference preference, Object o) { 

      String newValue = o.toString(); 
      sharedPreferences.edit().putString(deviceIdKey, newValue).apply(); 
      editTextPreference.setSummary(newValue); 
      return true; 
     } 
    }); 
} 
相關問題