Android - 如何计算一个编辑文本并除以另一个值?

Android - How to calculate one edit text and divide another value?

我完全是个初学者,我想知道是否有人可以帮助我解决代码问题。我正在尝试制作理想的日常饮水应用程序。

只有一个编辑文本供用户输入体重,我希望它除以例如 0.024。有按钮来计算,然后在屏幕上显示答案。

public class WaterCalculate extends Activity {

    //Declare textviews as fields, so they can be accessed throughout the activity.
    EditText weightuser;
    TextView tv4; 
    ImageButton calculate;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.water_calculate);

        //Bind the EditText views

        weightuser = (EditText)findViewById(R.id.weight);
        tv4 = (TextView)findViewById(R.id.res);

        calculate =  (ImageButton)findViewById(R.id.calc);
        calculate.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
               calculate();
        }
        });
    }

        private void calculate() {
             //get entered texts from the edittexts,and convert to integers.
            Double value1 = Double.parseDouble(weightuser.getText().toString());
            //do the calculation
            Double calculatedValue = (value1/0.024);
            //set the value to the textview, to display on screen.
            tv4.setText(String.valueOf("You need " + calculatedValue + "\nliters of water per day" ));
        }

}

当我 运行 应用程序计算按钮不起作用时,它显示应用程序已停止。感谢您的帮助。

试试下面的代码,确保它能正常工作,当你为按钮使用点击监听器时,你应该使用 View.Onclick

class WaterCalculate extends Activity {

    // Declare textviews as fields, so they can be accessed throughout the
    // activity.
    EditText weightuser;
    TextView tv4;
    ImageButton calculate;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.water_calculate);

        // Bind the EditText views

        weightuser = (EditText) findViewById(R.id.weight);
        tv4 = (TextView) findViewById(R.id.res);

        calculate = (ImageButton) findViewById(R.id.calc);

        calculate.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                calculate();
            }
        });
    }

    private void calculate() {
        // get entered texts from the edittexts,and convert to integers.
        Double value1 = Double.parseDouble(weightuser.getText().toString());
        // do the calculation
        Double calculatedValue = (value1 / 0.024);
        // set the value to the textview, to display on screen.
        tv4.setText(String.valueOf("You need " + calculatedValue
                + "\nliters of water per day"));
    }

}

我认为问题出在这一行。

 tv4.setText(String.valueOf("You need " + calculatedValue + "\nliters of water per day" ));

像这样试一试...

tv4.setText("You need "+Double.toString(calculatedValue)+"\nliters of water per day");

并确保您在必要的地方捕获了异常,例如将 editText 值转换为 double。