2
我希望應用程序在用戶將所請求的兩個值輸入到edittext中時自動計算,而不需要按鈕。使用TextWatcher獲取輸入到兩個edittext的值並將這些值相乘而不用按鈕。自動計算。
有沒有辦法做到這一點,而不使用TextWatcher?
這裏是我的嘗試。爲什麼不起作用?在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);
}}
'
好,我做了一個值試試這個
這樣你的。但是,當我刪除edittext中的值它再次崩潰。另外我想讓用戶在打開應用程序時看到空白的edittext,不想讓他看到零。任何想法如何我可以做到這一點?謝謝 –
'if(myEditText.getText()。toString().length()<1)myText =「0」;' – Geobits
James做了你所說的工作正常,但是應用程序仍然崩潰,當我刪除我輸入的值 –