EditText.getText.toString() 返回空字符串

huangapple go评论29阅读模式
英文:

EditText.getText.toString() is returning empty string

问题

我试图从EditText中恢复文本,但当我用Toast显示字符串时,我得到一个空字符串。

以下是代码部分:

view = inflater.inflate(R.layout.fragment_home, container, false);
EditText id = view.findViewById(R.id.busID);
busId = id.getText().toString();
btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(final View view) {
        Toast.makeText(getContext(), busId, Toast.LENGTH_LONG).show();
    }
});

以下是截图:

EditText.getText.toString() 返回空字符串

请帮助我。我不知道为什么它返回空字符串。

英文:

I am trying to recover the text from EditText but when I Toast the string I am getting an empty string.

Here is the code:

view =inflater.inflate(R.layout.fragment_home, container, false);
EditText id=view.findViewById(R.id.busID);
busId=id.getText().toString();
btn.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(final View view) {
          Toast.makeText(getContext(),busId,Toast.LENGTH_LONG).show();
     }
});

Here is the screenshot

EditText.getText.toString() 返回空字符串

Please help me out. I don't know why it is returning empty string

答案1

得分: 6

你正在过早提取EditText中的String

将您的代码更改如下:

btn.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(final View view) {
          busId = id.getText().toString();
          Toast.makeText(getContext(), busId, Toast.LENGTH_LONG).show();
     }
});
英文:

You are extracting the String from the EditText too early.

Change your code like this:

btn.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(final View view) {
          busId=id.getText().toString();
          Toast.makeText(getContext(),busId,Toast.LENGTH_LONG).show();
     }
});

huangapple
  • 本文由 发表于 2020年8月3日 19:03:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63228274.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定