可以使用以下方法:

  1. 在布局文件中添加两个 EditText 和一个 Button:
<EditText
    android:id="@+id/editText1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="请输入金额1"/>

<EditText
    android:id="@+id/editText2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="请输入金额2"/>

<Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="计算"/>
  1. 在 Activity 中获取 EditText 和 Button 对象,设置 Button 的点击事件监听器:
EditText editText1 = findViewById(R.id.editText1);
EditText editText2 = findViewById(R.id.editText2);
Button button = findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String text1 = editText1.getText().toString();
        String text2 = editText2.getText().toString();

        if (TextUtils.isEmpty(text1) || TextUtils.isEmpty(text2)) {
            Toast.makeText(MainActivity.this, "请输入金额", Toast.LENGTH_SHORT).show();
        } else {
            double amount1 = Double.parseDouble(text1);
            double amount2 = Double.parseDouble(text2);
            double result = amount1 + amount2;
            Toast.makeText(MainActivity.this, "金额总和为:" + result, Toast.LENGTH_SHORT).show();
        }
    }
});
  1. 在点击事件监听器中,先判断 EditText 中的文本是否为空,如果为空则弹出提示,否则将文本转换成 double 类型进行相加,并弹出结果提示。注意需要使用 TextUtils 类的静态方法 isEmpty() 判断字符串是否为空
安卓 两个 edittext 金额相加判断是否是空值

原文地址: https://www.cveoy.top/t/topic/eGPq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录