将 EditText 传递给 Toast
我正在尝试编写一个简单的程序,它将获取一个 editText 的内容,并在单击按钮后将其传递给 Toast。最初,这是一个在单击按钮时仅显示 Toast 的教程,但我想将 EditText 中的值传递到 Toast 的“text”参数。我在 Eclipse 中没有收到任何错误,但模拟器意外停止。
这是我的 java 代码:
package event.handling;
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.Toast;
public class HandlerExamples extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.testButton);
button.setOnClickListener(this);
}
public void onClick(View v) {
EditText text = (EditText)findViewById(R.id.edittext);
Toast toast = Toast (text);
toast.show();
}
private Toast Toast(EditText text) {
// TODO Auto-generated method stub
return null;
}
}
最终我将使用四个不同的 EditText 视图,并将输入的数字简单地添加在一起并在 Toast 中显示答案。
感谢您抽出时间!
I'm trying to write a simple program that will take the contents of one editText and pass it to a Toast after a button is clicked. Initially, this was a tutorial that simply displayed a Toast when the button is clicked, but I want to pass a value from the EditText to the 'text' parameter of Toast. I'm not getting any errors in Eclipse, but the emulator stops unexpectedly.
Here is my java code:
package event.handling;
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.Toast;
public class HandlerExamples extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.testButton);
button.setOnClickListener(this);
}
public void onClick(View v) {
EditText text = (EditText)findViewById(R.id.edittext);
Toast toast = Toast (text);
toast.show();
}
private Toast Toast(EditText text) {
// TODO Auto-generated method stub
return null;
}
}
Eventually I am going to use four different EditText views and simply add the numbers entered together and display the answer in a Toast.
Thanks for your time!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您从
Toast
方法返回 null,然后调用此 null 对象,因此您会得到NullPointerException
。它应该是这样的:
顺便说一句,这是一个不好的命名,我会推荐
private Toast toastFromEditText(EditText text)
或类似的。You return null from the
Toast
method and then call this null object, so you get aNullPointerException
.It should be something like this:
BTW, this is a bad naming, I would recommend
private Toast toastFromEditText(EditText text)
or similar.