我正在创建一个 PV = nRT 计算器,让用户输入三个给定变量中的任何一个。无需使用按钮,程序将自动检测已给出的三个变量,并自动计算第四个缺失的变量。这是我到目前为止的代码:
Thread calculate = new Thread(new Runnable() {
@Override
public void run() {
try {
if (Calculations.isCalcable(pressure.getText().toString(),
volume.getText().toString(),
moles.getText().toString(),
temperature.getText().toString()) == true) {
if (pressure.getText().toString().length() == 0) {
pressure.setText("1010");
} else if (volume.getText().toString().length() == 0) {
volume.setText("1010");
} else if (moles.getText().toString().length() == 0) {
moles.setText("1010");
} else {
temperature.setText("1010");
}
}
} catch (Exception e){
}
}
});
calculate.start();
这行不通。另外我不确定我是否真的应该使用线程。这是当我输入三个变量(R 变量是常量)时发生的情况:
在本例中,温度文本应更改为“1010”。
这是我的 isCalcable 类:
public class Calculations {
public static boolean isCalcable (String pressure, String volume, String moles, String temperature){
int hasNumber = 0;
if (pressure.length() > 0){
hasNumber++;
}
if (volume.length() > 0){
hasNumber++;
}
if (moles.length() > 0){
hasNumber++;
}
if (temperature.length() > 0){
hasNumber++;
}
if (hasNumber == 3){
return true;
}
return false;
}
}
我该怎么办?
最佳答案
你需要检测是否已经在上面输入了值 文本字段对吗?那你有没有看过TextWatcher ? Here is an example关于如何使用它。
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//code
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//code
}
@Override
public void afterTextChanged(Editable s) {
//code
}
});
基本上,您将 TextWatcher 应用于三个字段并进行观察。 如果所有三个字段都有您需要的值,则进行计算。
也许您可以向 Activity 添加全局变量,并在文本字段的 onTextChanged() 方法上检查这些全局变量,如果其中三个变量已经完成,请设置第四个变量的值。
关于java - 自动检查和计算不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24520929/