我正在设计一个基本的BMI计算器,我有一个计算器在工作,但我需要将计算出的答案从TextView转换为整数,以便使用<>运算符
如何将TextView中的答案转换为整数?
v.findViewById(R.id.bmi).setOnClickListener(this);
return v;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.bmi:
try {
EditText w = (EditText) getView().findViewById(R.id.w);
String value = w.getText().toString();
EditText h = (EditText) getView().findViewById(R.id.h);
String value1 = h.getText().toString();
TextView ans = (TextView) getView().findViewById(R.id.ans);
Double l1 = Double.parseDouble(value);
Double l2 = Double.parseDouble(value1);
ans.setText(Double.toString(l1 / (l2 * l2)));
}
catch (Exception e)
{
new AlertDialog.Builder(getActivity()).setNeutralButton("OK",null).setMessage("ALL FIELDS ARE REQUIRED TO COMPUTE YOUR BMI! ").show();
break;
}
}
}
}
首先,从textview
到int
的转换是NOT。text视图不是数据类型。如果您想要int中的结果,请使用parseInt()
方法。int i = Integer.parseInt(value)
。
[编辑]
试试这个,它会起作用的。
TextView tv = (TextView) findViewById(R.id.tv);
EditText et = (EditText) findViewById(R.id.et);
try {
double d = Double.valueOf(String.valueOf(et.getText()));
tv.setText(String.valueOf( (int) d));
}catch (NumberFormatException e){
Toast.makeText(MainActivity.this, "Enter valid number.", Toast.LENGTH_SHORT).show();
}
为了便于你理解,我把它简化了。代码仍然可以进行优化。