问题
i tried to call the setText() using the float but it dosnt seem to work can somone help me fix the problem?
public class Bmi extends MainActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bmi);
final EditText h = (EditText)findViewById(R.id.editText2);
final EditText w = (EditText)findViewById(R.id.editText3);
final TextView r = (TextView)findViewById(R.id.textView4);
Button calculate = (Button) findViewById(R.id.button1);
calculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
float height=0;
float weight=0;
float result=0;
height= Float.parseFloat(h.getText().toString());
weight= Float.parseFloat(w.getText().toString());
result = (weight/(height * height));
r.setText(result);
}
});
}
}
im trying to make a simple bmi calculator just as practice but im having issues on making it work
回答1:
You should convert your float to a String by
r.setText(String.valueOf(result));
Or the quick and dirty way
r.setText("" + result);
If you want it localized (Dot or Comma seperated decimal number)
String text = NumberFormat.getInstance(YOURCONTEXT.getResources().getConfiguration().locale).format(result);
r.setText(text);
Just replace YOURCONTEXT
with MainActivity.this
if you are in the MainActivity or getActivity()
if you are in a Fragment
If you want to set min or max fraction digits try this:
NumberFormat numberformat = NumberFormat.getInstance(YOURCONTEXT.getResources().getConfiguration().locale);
numberformat.setMaximumFractionDigits(2);
numberformat.setMaximumIntegerDigits(1);
numberformat.setMinimumFractionDigits(2);
String text = numberformat.format(result);
r.setText(text);
回答2:
You can use
r.setText(String.valueOf(result));
回答3:
In order to display float value inside TextView you'll need to convert it to String first.
You can convert any primitive data type(int, float, double,boolean,etc) to String by using String.valueOf(value) method.
Here value is the variable which you want to convert to String.
You can use
String str = String.valueOf(result);
r.setText(str);
Alternatively
r.setText(String.valueOf(result));
Please comment if further help is required.
来源:https://stackoverflow.com/questions/23791303/how-to-call-settext-using-a-float