其他分享
首页 > 其他分享> > android – 如何在EditTextPreference更改时显示新值

android – 如何在EditTextPreference更改时显示新值

作者:互联网

我的PreferenceActivity中有两个PreferenceActivity.

我的问题是当我更新项目时,新值不会反映在屏幕上.

public class HostSettingActivity extends PreferenceActivity {

    private final String MY_DEBUG_TAG = "SettingActivity";
    SharedPreferences sharedPrefs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.i(MY_DEBUG_TAG, "HostSettingActivity Started");
        super.onCreate(savedInstanceState);
        sharedPrefs = getPreferenceManager().getSharedPreferences(); 
        setPreferenceScreen(createPreferenceHierarchy());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(MY_DEBUG_TAG, "On Destroy");
    }

    private PreferenceScreen createPreferenceHierarchy() {

        // Root
        PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);


        PreferenceCategory dialogBasedPrefCat = new PreferenceCategory(this);
        dialogBasedPrefCat.setTitle("Host Settings");
        root.addPreference(dialogBasedPrefCat);

        EditTextPreference hostPreference = new EditTextPreference(this);
        hostPreference.setKey("host");
        hostPreference.setDialogTitle("Host");
        hostPreference.setDefaultValue("http://example.com");
        hostPreference.setSummary("Set host");
        dialogBasedPrefCat.addPreference(hostPreference);

        EditTextPreference portPreference = new EditTextPreference(this);
        portPreference.setKey("port");
        portPreference.setDialogTitle("Port");
        portPreference.setDefaultValue("8080");
        portPreference.setSummary("Set port");
        dialogBasedPrefCat.addPreference(portPreference);

        hostPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                EditTextPreference etp = (EditTextPreference) preference;
                String newHostValue = newValue.toString();
                Log.i(MY_DEBUG_TAG, "New Host: "+newHostValue);
                etp.setText(newHostValue);
                return true;
            }
        });
        return root;
    }

}

解决方法:

呼叫

preference.notifyChanged();

当它的数据发生变化时应该重新绘制.

标签:android,android-preferences
来源: https://codeday.me/bug/20190902/1794293.html