android - 如何使编辑文本既有符号又有十进制?

标签 android variables android-edittext

有没有办法将 edittext 设置更改为十进制 (3.4) 和单数 (+/-)? 我应该在我的 Activity 中设置什么类型的变量? 我尝试使用小数、数字并签名,但我想使用像 -3.6 这样的数字并将其存储在我的 Activity 中。

最佳答案

在你的 Activity 类中:

EditText editText = (EditText)findViewById(R.id.editText);
editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL);

来自 InputType | Android Developers

_____________ __________________ _________________ __________________________________

或者:

在你的 Activity 类中:

EditText editText = (EditText)findViewById(R.id.editText);
editText.setKeyListener(DigitsKeyListener.getInstance("0123456789.-"));

这允许 EditText 输入小数和负号,正如您在行尾看到的那样。

_____________ __________________ _________________ __________________________________

或者:

在您的 EditText XML 属性中,添加此属性:

android:inputType="numberSigned|numberDecimal"

_____________ __________________ _________________ __________________________________

您可以将数字输入到 String 中以存储输入的值:

EditText editText = (EditText)findViewById(R.id.editText);
String userInput = editText.getText().toString();

userInput 将等于用户输入的字符串。要将其转换为 double ,您可以这样做:

// however, this will break your app if you convert an empty String to a double
// so if there could be no text in the EditText, use a try-catch
double userInputDouble = Double.parseDouble(editText.getText().toString());

关于android - 如何使编辑文本既有符号又有十进制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19959710/