如何转换一个TextView的价值整数 [英] How do I convert the value of a TextView to integer
问题描述
我设计一个基本的BMI计算器和我有计算器的工作,但我需要计算的答案,从一个TextView转换这是一个双重一个整数,使我以&lt权的发言;>根据计算出答案运营商。结果
如何转换的答案从的TextView为整数?
v.findViewById(R.id.bmi).setOnClickListener(本); 返回伏;
}公共无效的onClick(视图v){ 开关(v.getId()){ 案例R.id.bmi: 尝试{
的EditText W =(EditText上)getView()findViewById(R.id.w)。
字符串值= w.getText()的toString()。
的EditText H =(EditText上)getView()findViewById(R.id.h)。
字符串值1 = h.getText()的toString()。 TextView的ANS =(TextView中)getView()findViewById(R.id.ans)。
双L1 = Double.parseDouble(值);
双L2 = Double.parseDouble(值);
ans.setText(Double.toString(L1 /(12 * 12))); }
赶上(例外五)
{
新AlertDialog.Builder(getActivity())setNeutralButton(OK,NULL).setMessage(所有的字段都需要计算你的BMI!).show();
打破;
} }}
}
首先,转换为不会从的TextView
到 INT
。 TextView的是不是一个数据类型。如果你想要的结果INT使用 parseInt函数()
方法。 INT I =的Integer.parseInt(值)
。
试试这个,这将工作。
TextView的电视=(的TextView)findViewById(R.id.tv);
等的EditText =(EditText上)findViewById(R.id.et);尝试{
双D = Double.valueOf(将String.valueOf(et.getText()));
tv.setText(将String.valueOf((INT)D));
}赶上(NumberFormatException的E){
Toast.makeText(MainActivity.this,输入有效的数字。Toast.LENGTH_SHORT).show();
}
我已经简化它的理解。在code仍可进行优化。
I am designing a basic BMI calculator and I have the calculator working, but I need to convert the calculated answer from a TextView which is a double to an integer to enable me right statements with <> operators based on the calculated answer.
How do I convert the answer from the TextView to an integer?
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;
}
}
}
}
First, The conversion is NOT from textview
to int
. textView aint a datatype. If you want the result in int use parseInt()
method. int i = Integer.parseInt(value)
.
[EDIT]
Try this, this will work.
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();
}
I have simplified it for your understanding. The code can still be optimized.
这篇关于如何转换一个TextView的价值整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!