动态创建的EditText:getText()不返回值

时间:2013-06-13 15:00:38

标签: android android-edittext

我正在尝试获取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>

2 个答案:

答案 0 :(得分:2)

getText会返回之前setText的结果。致电firstname.setText("your string")

在您提供的代码段中,用户没有时间输入文字。当你调用提交是迟到的。例如,您可以使用&#34;确认按钮&#34;当你点击它时,在你的编辑文本的onClick调用提交中,或者你可以实现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

}

答案 1 :(得分:2)

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