gpt4 book ai didi

java - 如何使用TextWatcher自动从edittext中获取值并相乘?

转载 作者:行者123 更新时间:2023-12-01 14:16:23 24 4
gpt4 key购买 nike

当我在编辑文本中输入数字时,应用程序强制关闭。我希望应用程序在输入值时自动计算 BMI,而无需按按钮。

我对 TextWatcher 一无所知,但我研究并提出了这段代码。但它不起作用。有什么问题吗?

public class BodyMassIndex extends Activity implements View.OnClickListener,
TextWatcher {

double result;
EditText age, height, weight;
ToggleButton sex, cmin, kglb;
TextView tvResult;
double heightInt = 1;
double weightInt = 0;
int ageInt;

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

sex.setOnClickListener(this);
cmin.setOnClickListener(this);
kglb.setOnClickListener(this);


}

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);
sex = (ToggleButton) findViewById(R.id.tbSex);
cmin = (ToggleButton) findViewById(R.id.tbCMIN);
kglb = (ToggleButton) findViewById(R.id.tbKGLB);
tvResult = (TextView) findViewById(R.id.tvResult);
age.addTextChangedListener(this);
height.addTextChangedListener(this);
weight.addTextChangedListener(this);
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

switch (v.getId()) {
case R.id.tbCMIN:
heightInt = heightInt * 0.0254;
break;
case R.id.tbKGLB:
weightInt = weightInt * 0.45359237;
break;
}

}

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

private void calculate() {
// TODO Auto-generated method stub
Editable H = height.getText(), W = weight.getText();

if(H != null)
heightInt = Double.parseDouble(H.toString());
if (W != null)
weightInt = Double.parseDouble(W.toString());

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

@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

}
}

'

最佳答案

来自http://developer.android.com/reference/android/text/TextWatcher.html关于 afterTextChanged 方法: "但要小心不要让自己陷入无限循环,因为你所做的任何更改都会导致该方法再次递归调用....你可以使用 setSpan(Object, int, int, int )在 onTextChanged(CharSequence, int, int, int) "

关于java - 如何使用TextWatcher自动从edittext中获取值并相乘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18070821/

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