我有这个按钮调用两个方法。见代码;现在我尝试在onPictureSubmit(v)方法上添加一个方法,如果有人在没有提交答案的情况下点击按钮,它将打印Toast消息(请提交答案)。问题是它一直在破碎。如果我能够检测到某人点击按钮而不提交答案的任何帮助将不胜感激。
我的按钮代码;
@Override
public void onClick(View v) {
switch (pass) {
case 0:
onDefinitionSubmit(v);
break;
case 1:
onPictureSubmit(v);
break;
case 2
break;
}
}
我的代码:
private void onPictureSubmit(View v) {
if (v.getId() == R.id.picture_submit) {
final int answerGiven = Integer.parseInt("" + ((EditText) findViewById(R.id.picture_answer)).getText());
final int answerKey = com.madonasystematixnote.mathhelper.lessons.PictureFragment.answer;
final int x = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_x)).getText());
final int y = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_y)).getText());
}
}
答案 0 :(得分:1)
如果我是你,我会将TextView
,EditText
,Button
声明为全局变量,然后在onCreate()
I {d}中声明使用findViewById()
来避免NullPointerException
。
其次,我检查answerGiven
(我猜是答案)是否为空,所以我创建了一个方法,如果它已经返回给我是否清空EditText
。
public boolean isEtEmpty(String str){
if(str.isEmpty() || str.length() == 0 || str.equals("") || str == null){
return true;
}
else{
return false;
}
}
然后在你致电onPictureSubmit()
时,请调用此方法:
if (v.getId() == R.id.picture_submit) {
if (isEtEmpty(picture_answer.getText())){ //picture_answer is the EditText that you want to know if it's empty or not
Toast.makeText(v.getContext(), "Please Submit Answer",Toast.LENGTH_LONG).show();
}
else{
final int answerGiven = Integer.parseInt("" + ((EditText) findViewById(R.id.picture_answer)).getText());
final int answerKey = com.madonasystematixnote.mathhelper.lessons.PictureFragment.answer;
final int x = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_x)).getText());
final int y = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_y)).getText());
}
}