首页 > 解决方案 > 如果 EditText 留空,如何将其设置为 0

问题描述

基本上我有四个 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 并且仍然给出购买的总水果?

标签: android

解决方案


private String ensureFruit(String str){

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

}

并将其用作

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

推荐阅读