gpt4 book ai didi

android - 如何计算 Android 中的 EditText 值?

转载 作者:行者123 更新时间:2023-11-29 14:34:04 25 4
gpt4 key购买 nike

在 Android 应用程序中,我使用了两个 EditText 控件并将它们的两个值相乘。如果一个 EditTextnull 而在第二个中我输入了一个值,它就无法正常工作。我该如何处理这种情况,我在一个 EditText 中有一个值,在另一个中有一个 null,我想将这两个值相乘?

最佳答案

首先,您需要有一个触发器来确定何时执行计算。假设它是一个按钮,或者更好的是,每当您的 EditText 之一的值发生变化时:

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 - 如何计算 Android 中的 EditText 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6965063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com