使用TextWatcher将输入的值输入到两个edittext中,并在没有按钮的情况下将这些值相乘。自动计算。

时间:2013-08-06 22:11:15

标签: java android textwatcher

我希望应用程序在用户将所请求的两个值输入edittext时自动计算,而无需按钮。

有没有办法在不使用TextWatcher的情况下完成?

这是我的尝试。为什么它不起作用?在edittext中输入数字时,app force会关闭。

'

public class BodyMassIndex extends Activity

{

double result;
    EditText age, height, weight;

TextView tvResult;

int ageInt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.bmi);
    initialize();

    TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            calculate();

        }



        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub

        }

    };

    height.addTextChangedListener(textWatcher);
    weight.addTextChangedListener(textWatcher);

}

private void initialize() {
    // TODO Auto-generated method stub

    age = (EditText) findViewById(R.id.etAge);
    height = (EditText) findViewById(R.id.etHeight);
    weight = (EditText) findViewById(R.id.etWeight);

    tvResult = (TextView) findViewById(R.id.tvResult);


}

private void calculate() {
    // TODO Auto-generated method stub


    double heightInt = 1;
    double weightInt = 0;

    if (height != null)
        heightInt = Double.parseDouble(height.getText().toString());

    if (weight != null)
        weightInt = Double.parseDouble(weight.getText().toString());

    result = weightInt / (heightInt * heightInt);
    String textResult = "Your BMI is " + result;
    tvResult.setText(textResult);




}}
'

1 个答案:

答案 0 :(得分:2)

你应该将edittext的默认值设置为0.它可能强制关闭,因为你试图从一个没有任何内容的edittext中解析一个空字符串;

编辑:试试这个

if (height != null)
    heightInt = Double.parseDouble(!height.getText().toString().equals("")?
           height.getText().toString() : "0");

if (weight != null)
    weightInt = Double.parseDouble(!weight.getText().toString().equals("")?
           weight.getText().toString() : "0");

这样你使用的条件无论你将解析一个不会抛出异常的值