问题描述
Add.setonClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
float firstValue,secondValue,ans ;
firstValue = Float.parseFloat( etFirstValue.getText().toString());
secondValue = Float.parseFloat( etSecondValue.getText().toString());
ans = firstValue + secondValue;
tvAnswer.setText("Ans = " + ans);
}
});
这是我添加按钮单击的编码,输入值后所有按钮都可以正常工作。但是当我在输入值之前单击按钮时会出现问题,我的应用程序突然停止工作。解决这个问题,让我在输入值之前点击按钮时不会发生任何事情。
解决方法
Add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
float firstValue=0,secondValue=0,ans=0 ;
if (etFirstValue.length()>0&& (etSecondValue.length()>0)
{
firstValue = Float.parseFloat(etFirstValue.getText().toString());
secondValue = Float.parseFloat(etSecondValue.getText().toString());
tvAnswer.setText("Ans = " + ans);
} else {
Toast.makeText(MainActivity.this,"Enter the Values First",Toast.LENGTH_SHORT).show();
}
ans = firstValue + secondValue;
tvAnswer.setText("Ans = " + ans);
}
});
我自己解决了这个问题。 现在它不会崩溃,只是发出警告消息“首先输入值” 感谢大家付出宝贵的时间。
,就这样去做
首先将您的值转换为字符串,然后执行此操作:
if(value1.matches("")){
Toast(context,"Please Fill First Value",LENGTH_SHORT).show();
return;
}
else if(value2.matches("")){
Toast(context,LENGTH_SHORT).show();
return;
}
else{
//Continue With Your Code
//Do Calculations Or Anything
}
注意:使用您自己的来自 EditText 的值更改 Value1、Value2
, Add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
float firstValue=null,secondValue=null,ans=0; //initialise the value here
firstValue = Float.parseFloat( etFirstValue.getText().toString());
secondValue = Float.parseFloat( etSecondValue.getText().toString());
if(firstValue==null&&secondvValue==null)
{
tvAnswer.setText("Ans = " + ans);
} else{
ans = firstValue + secondValue;
tvAnswer.setText("Ans = " + ans);
}
}
});
如果上述方法不起作用,请将以上所有值初始化为零而不是 null。