2

I want the app to automatically compute when the user enters the requested two values into edittext, without needing a button.

Is there a way to do it without using TextWatcher?

here is my attempt. Why doesnt it work? The app force shuts when a number is entered in edittext.

'

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);




}}
'
4

1 回答 1

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");

这样,您就可以使用一个条件,无论您要解析什么值,都不会引发异常

于 2013-08-06T22:14:25.650 回答