How do I convert the value of a TextView to integer

拟墨画扇 提交于 2019-12-11 11:46:22

问题


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;
            }

    }

}
}

回答1:


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.



来源:https://stackoverflow.com/questions/34481587/how-do-i-convert-the-value-of-a-textview-to-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!