简体   繁体   English

EditText获取toString

[英]EditText get toString

This is my code but i can't fill my string with the value put in by the user. 这是我的代码,但是我无法用用户输入的值填充字符串。

I've tried a lot of solutions from other sites but it won't work. 我已经尝试了其他站点的许多解决方案,但无法正常工作。

package app.android.Mel

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class RedFlashlightActivity extends Activity {

private EditText text;
private TextView myRecord;
private Button myButton;

/** Called when the activity is first created. */
@Override

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    text = (EditText) findViewById(R.id.txtName);
    myButton = (Button) this.findViewById(R.id.myButton);
    myRecord = (TextView) findViewById(R.id.myRecord);
    final String rec = text.getText().toString();

    myButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            myRecord.setText(rec);
            Toast.makeText(RedFlashlightActivity.this,rec, Toast.LENGTH_SHORT).show();
        }

    });
}
}

The point is that rec is created once at the activity creation time and doesn't change ever after( it is final ). 关键是,rec在活动创建时创建一次,并且此后永远不会更改(它是final)。 Just replace 只需更换

myRecord.setText(rec);

with

myRecord.setText(text.getText().toString());
    myButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        String rec = text.getText().toString();
        myRecord.setText(rec);
        Toast.makeText(RedFlashlightActivity.this,rec, Toast.LENGTH_SHORT).show();
    }
});

Move the rec = text.getText().toString() into the OnClickListener event handler class. rec = text.getText().toString()移到OnClickListener事件处理程序类中。 Then it should work. 然后它应该工作。 Otherwise it will take a null value, because you're using the String rec , which is constructed during the Activity creation phase. 否则,它将采用null值,因为您使用的是在Activity创建阶段构造的String rec

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM