如何在Android中计算的EditText价值? [英] How to calculate EditText value in Android?

查看:161
本文介绍了如何在Android中计算的EditText价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个Android应用程序,我用两个的EditText 控制及其两个值相乘。
如果有一个的EditText ,并在第二个我把一个价值,它不能正常工作。
我该如何处理这种情况下,我有一个的EditText A 在对方的值,并且我想乘两个值?

In an Android app, I'm using two EditText controls and multiplying their two values. If one EditText is null and in the second one I put a value, it's not working properly. How can I deal with this case, in which I have a value in one EditText and a null in the other and I want to multiply the two values?

推荐答案

首先,你需要有对何时执行计算的触发器。说这是一个按钮,或者,甚至更好,每一次你的的EditText 变迁之一的值:

First of all, you need to have a trigger for when to perform the calculation. Say it's a button, or, even better, every time the value of one of your EditTexts changes:

private EditText editText1,
                 editText2;
private TextView resultsText;

...............................

// Obtains references to your components, assumes you have them defined
// within your Activity's layout file
editText1 = (EditText)findViewById(R.id.editText1);
editText2 = (EditText)findViewById(R.id.editText2);

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

// Instantiates a TextWatcher, to observe your EditTexts' value changes
// and trigger the result calculation
TextWatcher textWatcher = new TextWatcher() {
    public void afterTextChanged(Editable s) {
        calculateResult();
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after){}
    public void onTextChanged(CharSequence s, int start, int before, int count){}
};

// Adds the TextWatcher as TextChangedListener to both EditTexts
editText1.addTextChangedListener(textWatcher);
editText2.addTextChangedListener(textWatcher);

.....................................

// The function called to calculate and display the result of the multiplication
private void calculateResult() throws NumberFormatException {
  // Gets the two EditText controls' Editable values
  Editable editableValue1 = editText1.getText(),
           editableValue2 = editText2.getText();

  // Initializes the double values and result
  double value1 = 0.0,
         value2 = 0.0,
         result;

  // If the Editable values are not null, obtains their double values by parsing
  if (editableValue1 != null)
    value1 = Double.parseDouble(editableValue1.toString());

  if (editableValue2 != null)
    value2 = Double.parseDouble(editableValue2.toString());

  // Calculates the result
  result = value1 * value2;

  // Displays the calculated result
  resultsText.setText(result.toString());
}

这篇关于如何在Android中计算的EditText价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆