【问题标题】:EditText get toStringEditText 获取 toString
【发布时间】:2010-10-27 08:00:52
【问题描述】:

这是我的代码,但我无法用用户输入的值填充我的字符串。

我尝试了很多其他网站的解决方案,但都行不通。

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();
        }

    });
}
}

【问题讨论】:

    标签: java android tostring android-edittext


    【解决方案1】:

    关键是 rec 在活动创建时创建一次,之后就永远不会改变(它是 final )。 只需替换

    myRecord.setText(rec);
    

    myRecord.setText(text.getText().toString());
    

    【讨论】:

      【解决方案2】:
          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();
          }
      });
      

      【讨论】:

        【解决方案3】:

        rec = text.getText().toString() 移动到OnClickListener 事件处理程序类中。然后它应该工作。否则它将采用空值,因为您使用的是String rec,它是在Activity 创建阶段构建的。

        【讨论】:

          猜你喜欢
          • 2013-07-02
          • 1970-01-01
          • 2012-12-25
          • 1970-01-01
          • 1970-01-01
          • 2012-09-06
          • 2013-10-12
          • 1970-01-01
          • 2023-03-14
          相关资源
          最近更新 更多