android - 如果 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 并且仍然给出购买的总水果?
解决方案
private String ensureFruit(String str){
return TextUtils.isEmpty(str)? "0": str;
}
并将其用作
float apple = Float.parseFloat(ensureFruit(a.getText().toString()));
推荐阅读
- swift - Swift按案例名称对枚举进行排序
- javascript - 如何从 Python CGI 脚本中返回一个值
- r - 使用 RpostgreSQL 在循环内更改 PostgreSQL 架构
- php - 如何在 unicode 字符串中找到相似的 unicode 文本?
- java - 是否有必要在 JPanel 上调用 setDoubleBuffered?
- html - 隐藏菜单主滑块并在页面向下滚动时激活它
- django - 如何检查 PostgreSQL 中的数据是否被删除
- elasticsearch - Elasticsearch 中嵌套索引结构的多个 (AND) 查询
- jasper-reports - 为什么我的报告从 JasperReports 6.2.2+ 中断?
- cmake - 如何在 CMake 中仅在构建系统而不是目标系统上定义依赖关系