将当前SeekBarPreference值显示到ScreenPreference中

时间:2016-05-21 12:26:10

标签: java android android-preferences seekbar

将SeekBarPreference的当前值显示到ScreenPreference中的好方法是什么。 我试图插入textview但应用程序崩溃了。 有什么建议吗?

的preferences.xml

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
  <SeekBarPreference
      android:id="@+id/seekbar_pref"
      android:key="seekbar_x"
      android:title="Value"
      android:defaultValue="1"
      android:max="60"/>
  </PreferenceScreen>

Preferences.java 公共类首选项扩展了PreferenceActivity {

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

public static class MyPreferenceFragment extends PreferenceFragment
{
    @Override
    public void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }
}

Main.java

private SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            Log.e("SHARED",  "VAL: " + sharedPreferences.getInt("seekbar_x",10));
        }
    };

1 个答案:

答案 0 :(得分:0)

onCreate方法中,在最后添加此行(添加首选项后):

SeekBarPreference pref = (SeekBarPreference) findPreference("seekbar_pref");

然后像这样添加监听器:

pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
    int value = mSeekBarPreference.getProgress(); //or (int)  newValue
    //You can now use this value wherever you like:
    pref.setSummary("Value: " + value);
    return true;
}
});