4

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

4

1 回答 1

4

In your activity class:

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

from InputType | Android Developers

__________________________________________________________________________________

OR:

In your activity class:

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

That allows the EditText to input decimals and negative signs, as you can see at the end of the line.

__________________________________________________________________________________

OR:

In your EditText XML properties, add this property:

android:inputType="numberSigned|numberDecimal"

__________________________________________________________________________________

You can input the number to a String to store the value inputted:

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

userInput will then be equal to the String that the user inputted. To convert it to a double, you can do this:

// 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());
于 2013-11-14T18:42:16.263 回答