如果用户点击一个按钮,我想在每个“空”文本框中设置一个“0”,以避免应用程序中的错误,任何帮助?我不知道该怎么做
package com.doko.most;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.view.View;
public class doko extends Activity {
private EditText bx1;
private EditText bx2;
private TextView txt3;
private Button btncalcular;
private Button btnreset;
private double variable1 = 0;
private double variable2 = 0;
private double variable3 = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls()
{
bx1 = (EditText)findViewById(R.id.bx1);
bx2 = (EditText)findViewById(R.id.bx2);
txt3 = (TextView)findViewById(R.id.txt3);
btncalcular = (Button)findViewById(R.id.btncalcular);
btnreset = (Button)findViewById(R.id.btnreset);
btncalcular.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ calcular(); }});
btnreset.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ reset(); }});
}
private void calcular()
{
variable1 = Double.parseDouble(bx1.getText().toString());
variable2 = Double.parseDouble(bx2.getText().toString());
variable3 = Math.sqrt(1*2/3600);
txt3.setText(Double.toString(variable3));
}
private void reset(){
bx1.setText("");
bx2.setText("");
}
}
答案 0 :(得分:0)
在EditText中设置Hint属性 防爆。
并在getText()
时检查它使用str.isEmpty()和str.length来检查用户的inpupt
另一种方式: 将EditText的inputType设置为数字并设置输入过滤器 离。InputFilter [] FilterArray = new InputFilter [1];
FilterArray [0] = new InputFilter.LengthFilter(4);
input.setFilters(FilterArray);
答案 1 :(得分:0)
尝试类似这样的事情,快速而肮脏:
private void calcular() {
try {
variable1 = Double.parseDouble(bx1.getText().toString());
}
catch(NumberFormatException e) {
bx1.setText("0");
}
try {
variable2 = Double.parseDouble(bx2.getText().toString());
}
catch(NumberFormatException e) {
bx2.setText("0");
}
variable3 = Math.sqrt(1*2/3600);
txt3.setText(Double.toString(3));
}