开发者

Parsing a value with a dimension in Android

What is the proper way to parse a value with a dimension in Android? For example, I would want to get an int with a value of 20 from any of these strings: 20px, 20mm, 20dp.

Trying Integer.parseInt() doesn't get me very far because开发者_StackOverflow社区 it throws an exception on non-numeric characters.


If the unit is always present and is only one of the mentioned AND you are sure you won't ever need it - simply parse a substring str.substring(0, str.length() - 3)

I would recommend using a custom class to parse and hold the value including the unit - you might need it sometime.


If you start with an AttributeSet, you can obtain a TypedArray through a Context and eventually use getDimension or a related function.

If you just want to pass a string to parseInt without throwing an exception try this:

Integer.parseInt( someString.replaceFirst( "[^0-9].*" , "" ) );

The regular expression truncates the string starting at the first character that is not a digit. Which implies that the string must start with a digit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜