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

时间:2015-08-22 05:15:50

标签: android android-edittext

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

只有一个编辑文本供用户输入其重量,我希望它除以例如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" ));
        }

}

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

2 个答案:

答案 0 :(得分:0)

我认为问题出在这一行。

 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。

答案 1 :(得分:-1)

尝试下面的代码,我相信它会起作用,当你使用点击监听器按钮时,你应该使用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"));
    }

}