如何从也具有字符串的TextView中获取数字

时间:2015-07-31 05:36:41

标签: android android-edittext textview

我有两个TextView显示来自几个EditText框的平均值,并将其显示为“我的平均值:245”,另一个Textview显示 “我的平均值:145”。我在按钮点击时计算这两个TextView中的平均值,并将按钮的文本设置为答案。如何从文本视图中仅获取数字?因为在TextView上调用Double.parseDouble()时,我收到错误。任何帮助将不胜感激,谢谢。 enter image description here

4 个答案:

答案 0 :(得分:3)

从所有EditText中获取String并使用Regex从字符串中提取数字。检查以下示例:

String str = "My Avg: 145";
Pattern pattern = Pattern.compile("(\\d+)");
Matcher m = pattern.matcher( str );

if( m.find() ){
    String i=m.group(); 
    System.out.println( "-->>" + i);
}

这里

\d means one digit 
\d+ means one or more digits
() means capture that group 

此regrx将为您提供字符串中的第一组数字。您可以使用i

解析double.parse();

答案 1 :(得分:2)

您可以从文本视图中获取数字,如下所示:

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

if (!textView.equals("") && !textView.equals(......)) {
    int num = Integer.parseInt(textView);//extract number from text view  
} 

答案 2 :(得分:2)

通过计算textview中的平均值,你是什么意思?无论你在哪里进行计算,你都应该能够访问这些值,尝试从textview中解析值不是一个很好的做法。

分享你的代码和你得到的错误,我猜你正试图用textview的完整字符串解析值,并且,你可以想象,不可能从字符串中获取Double值

如果字符串My avg:永远不会更改,那么您将从“:”符号中拆分此字符串并修剪该值。

String text = "My avg: 245";

String numberString = text.split(":")[1];
Double number = Double.parseDouble(numberString);

System.out.println(number);

输出是:

245.0

我坚持认为你不应该这样做,如果文字因任何原因而改变,你的应用程序就会破解。

答案 3 :(得分:1)

您无法直接在Double#parseDouble上致电String,因为它可能会NumberFormatException,如果它不是数字。

所以,你必须先从中获取数字。您可以使用String#split

来完成此操作

使用TextView#getText()

获取字符串

使用

拆分文本
String[] val =  textViewText.split(":");

这将返回一个数组,然后您可以调用Double.parseDouble

double num = Double.parseDouble(val[1].trim());