如何使edittext既包括signed也包含十进制?

时间:2013-11-13 16:53:11

标签: android variables android-edittext

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

1 个答案:

答案 0 :(得分:2)

在您的活动课程中:

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

<强> _ __ _ __ _ __ _ __ _ 的__ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ < / EM> __ _ __ _ __ _ __ _ __ _ ___ < /强>

OR:

在您的活动课程中:

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

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

<强> _ __ _ __ _ __ _ __ _ 的__ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ < / EM> __ _ __ _ __ _ __ _ __ _ ___ < /强>

OR:

EditText XML属性中,添加以下属性:

android:inputType="numberSigned|numberDecimal"

<强> _ __ _ __ _ __ _ __ _ 的__ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ < / EM> __ _ __ _ __ _ __ _ __ _ ___ < /强>

您可以将号码输入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());