我创建了一个简单的程序来试图弄清楚如何做到这一点。它有两个编辑文本字段(输入类型编号十进制),一个文本视图和一个按钮。我希望当用户点击按钮时,两个输入字段的总和将显示在文本视图中。如果用户将其留空,有人可以告诉我如何将一个编辑文本字段的值设置为零吗?我尝试了很多方法,但没有任何效果。编辑:我希望在保持编辑文本提示的同时实现这一点(不像“setText(”0“)那样将值更改为零;”。
这是我的java代码(告诉我要添加什么)
package com.example.android.testedittexttozero;
import...
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void calculate(View v) { //the button
final EditText number1 = (EditText) findViewById(R.id.numberFirst);
EditText number2 = (EditText) findViewById(R.id.numberSecond);
TextView total = (TextView) findViewById(R.id.totalTV);
try {
int a = Integer.parseInt(number1.getText().toString());
int b = Integer.parseInt(number2.getText().toString());
int sum = a + b;
total.setText("" + sum);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "One or more field is empty", Toast.LENGTH_LONG).show();
}
}
}
你知道在java中如果你没有用默认值初始化变量,它的默认值是0吗?简而言之:
try {
int a;//by default, it will be 0;
int b = Integer.parseInt(number2.getText().toString());//let it be 2
int sum = a + b;
total.setText("" + sum);//Ans will be 2 only
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "One or more field is empty", Toast.LENGTH_LONG).show();
}
如果你没有在a中输入任何值,它将被设置为0.就像你留空,并在第二个edittext中输入2,但是ans将是两个..
public void ZeroingEmpytEditText() {
int f= 0; // Zeroing Factor
if (number1.getText().toString().length() > 0) {
a = Integer.parseInt(number1.getText().toString());
} else {
a=f;
}
if (number2.getText().toString().length() > 0) {
b = Integer.parseInt(number2.getText().toString());
} else {
b=f;
}
int sum = a + b ;
total.setText(sum + "");
}
您可以在oncreate方法中设置编辑文本的值0。喜欢,
public class MainActivity extends AppCompatActivity {
EditText number1,number2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number1 = (EditText) findViewById(R.id.numberFirst);
number2 = (EditText) findViewById(R.id.numberSecond);
number1.settext("0");
number2.settext("0");
}
public void calculate(View v) { //the button
TextView total = (TextView) findViewById(R.id.totalTV);
try {
int a = Integer.parseInt(number1.getText().toString());
int b = Integer.parseInt(number2.getText().toString());
int sum = a + b;
total.setText("" + sum);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "One or more field is empty", Toast.LENGTH_LONG).show();
}
}
}
它对你有帮助。