Android how to set default value of EditTextPreference from SharedPreference?

拈花ヽ惹草 提交于 2019-12-05 10:23:47

Okay guys, I got it:

import android.preference.EditTextPreference;

public class Settings extends PreferenceActivity {


    EditTextPreference weightEditTextPreference;
    EditTextPreference ageEditTextPreference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);

        weightEditTextPreference = (EditTextPreference)findPreference("weight");
        ageEditTextPreference = (EditTextPreference)findPreference("age");

        SharedPreferences getWeightAndAgeStore = getSharedPreferences("weightAndAgeStorage", Context.MODE_PRIVATE);
        weightEditTextPreference.setText(getWeightAndAgeStore.getString("weight", "0"));
        ageEditTextPreference.setText(getWeightAndAgeStore.getString("age", "0"));

What this does is that it sets the EditText box to the SharedPreferences' saved key (in this case, weight and age of WeightAndAgeStorage) data in the dialog that pops up when you press it.

Hope anyone else reading this now or in the future (but what about the past?) benefits from this finding.

Cheers!

Firstly, set the default value for EditTextPreference. The value will be stored as a String type. For example:

<EditTextPreference
    android:key="weight"
    android:defaultValue="enter your value (54)"
    ... />

<EditTextPreference
    android:key="age"
    android:defaultValue="enter your value"
    ... />

Then, apply the default value in activity where your app's activity is started first (once installed for first). For example, in the MainActivity's onCreate() method:

PreferenceManager.setDefaultValue(this, R.xml.settings, false);

All you have to do is use the sharedPreferences.getString() and then use the editext.setText() to that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!