setText不适用于EditTextPreference

时间:2011-09-27 12:34:04

标签: android android-preferences

我正在尝试为EditTextPreference item

设置值

hostPreference.setText("Not yet set");

但是文字没有显示

enter image description here

我想在Use Name这里显示

enter image description here

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.setText("Not yet set");
        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;
    }

}

2 个答案:

答案 0 :(得分:3)

在EditTextPreference中看不到文本,但可以编辑。

看到的是 TITLE ,它由setTitle设置。

如果要在标题中显示已编辑的文本,则必须自己将其设置为标题。

答案 1 :(得分:2)

我认为你将setTextsetTitle混淆......