0

我正在尝试获取 editText 的值并将其存储在共享首选项中,我这样做了:

SharedPreferences participant;
    Editor editor;
    private EditText firstname = null;
    private String name =null;
    private LinearLayout formbis;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_participant);

        participant = this.getSharedPreferences("participant", getBaseContext().MODE_PRIVATE);
        editor = participant.edit();


        formbis = (LinearLayout) findViewById(R.id.formbis);



        firstname = new EditText(this);
        firstname.setHint("first name");
        firstname.setTextSize(12);
        firstname.setLayoutParams(new LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT));
        name = firstname.getText().toString();
        editor.putString("key", name);
        editor.commit();

        formbis.addView(firstname);

但是当我打开 sharedPreferences XML 文件时,我只发现:editText 中没有值:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="key"></string>
</map>
4

2 回答 2

2

getText返回前一个的结果setText。打电话firstname.setText("your string")

在您提供的代码段中,用户没有时间输入文本。当您调用提交时,为时已晚。例如,您可以有一个“确认按钮”,当您单击它时,在onClick您的 edittext 上的调用提交中,或者您可以实现TextWatcher

private class MyTextWather implements TextWatcher {


    @Override
    public void afterTextChanged(Editable s) {
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before,
            int count) {
         // it is called every time you put something inside your edittext

}
于 2013-06-13T15:01:59.713 回答
2

您需要向您添加一个侦听器EditText,然后在用户输入一些文本时提交该值。

于 2013-06-13T15:05:55.823 回答