如果将EditText留空,如何将其设置为0

时间:2019-04-16 15:38:26

标签: android

基本上,我有四个EditText字段,可以将它们称为苹果,梨,香蕉和橙色。用户输入每笔购买的数量,然后当您按下按钮时,它将计算总水果数。

public class Fruit extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fruit);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        setTitle("Enter amount of fruit bought");
    }

    public void onButtonClick(View v) {
        EditText a = (EditText)findViewById(R.id.editText3);
        EditText p = (EditText)findViewById(R.id.editText5);
        EditText b = (EditText)findViewById(R.id.editText4);
        EditText o = (EditText)findViewById(R.id.editText6);
        TextView sum = (TextView)findViewById(R.id.textView3);

        float apple = Float.parseFloat(a.getText().toString());
        float pear = Float.parseFloat(p.getText().toString());
        float banana = Float.parseFloat(b.getText().toString());
        float orange = Float.parseFloat(o.getText().toString());
        float total;


        total=apple+pear+banana+orange;

        sum.setText(Float.toString(total));

    }}

如何确定用户是否将字段保留为空白,程序会将其视为0并仍然给出购买的总水果量?

1 个答案:

答案 0 :(得分:1)

private String ensureFruit(String str){

     return TextUtils.isEmpty(str)? "0": str;

}

并将其用作

float apple = Float.parseFloat(ensureFruit(a.getText().toString()));