将textview中的数字转换为int [英] Convert number in textview to int

查看:423
本文介绍了将textview中的数字转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我在搞怪Java/android编程,现在我正在尝试制作一个真正的基本计算器.不过,我在这个问题上挂了电话.这是我现在拥有的代码,用于获取textview中的数字并将其设为int

So, I am messing around with java/android programming and right now I am trying to make a really basic calculator. I am hung up on this issue though. This is the code I have right now for getting the number thats in the textview and making it an int

CharSequence value1 = getText(R.id.textView);
int num1 =  Integer.parseInt(value1.toString());

据我所知,第二行是导致错误的原因,但我不确定为什么会这样做.它可以很好地编译,但是当它尝试运行程序的这一部分时,它使我的应用程序崩溃了.而在文本视图中,唯一的事情就是数字

And from what I can tell it is the second line that is causing the error, but im not sure why it is doing that. It is compiling fine, but when it tries to run this part of the program it crashes my app. And the only thing thats in the textview is numbers

有什么建议吗?

如果需要,我还可以提供更多代码

I can also provide more of my code if necessary

推荐答案

您可以阅读的用法TextView .

如何声明:

TextView tv;

初始化它:

tv = (TextView) findViewById(R.id.textView);

或:

tv = new TextView(MyActivity.this);

或者,如果您要放大布局,

or, if you are inflating a layout,

tv = (TextView) inflatedView.findViewById(R.id.textView);

要将字符串设置为tv,请使用tv.setText(some_string)tv.setText("this_string").如果需要设置整数值,请使用tv.setText("" + 5),因为setText()是可以处理字符串和int参数的重载方法.

To set a string to tv, use tv.setText(some_string) or tv.setText("this_string"). If you need to set an integer value, use tv.setText("" + 5) as setText() is an overloaded method that can handle string and int arguments.

要从tv获取值,请使用tv.getText().

始终检查解析器是否可以处理textView.getText().toString()可以提供的可能值.如果尝试解析空字符串("),则会抛出NumberFormatException.或者,如果您尝试解析..

Always check if the parser can handle the possible values that textView.getText().toString() can supply. A NumberFormatException is thrown if you try to parse an empty string(""). Or, if you try to parse ..

String tvValue = tv.getText().toString();

if (!tvValue.equals("") && !tvValue.equals(......)) {
    int num1 = Integer.parseInt(tvValue);
}

这篇关于将textview中的数字转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆