以编程方式设置编辑文本数字

我实际上是在尝试通过编程方式设置 EditText 的数字值:

weightInput.setInputType(InputType.TYPE_CLASS_PHONE);
weightInput.setKeyListener(DigitsKeyListener.getInstance());

这很好,但是我也希望能够包含一个小数位(.)。有什么想法吗?

87148 次浏览

Try this:

<EditText
android:inputType="number"
android:digits="0123456789."
/>

From Code:

weightInput.setKeyListener(DigitsKeyListener.getInstance("0123456789."));

But, it allows the user to include several "." See JoeyRA's answer for real numbers.

Use InputType.TYPE_NUMBER_FLAG_DECIMAL.

Also see: Input Types.

For IP address input ( Multiple dots and numbers )

try

<EditText
android:id="@+id/ipBox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/ipAddrHint"
android:inputType="numberDecimal|number"
android:digits="0123456789."
android:textSize="30sp" />

Try this:

weightInput.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
weightInput.setKeyListener(DigitsKeyListener.getInstance(false,true));

public static DigitsKeyListener getInstance (boolean sign, boolean decimal)

Returns a DigitsKeyListener that accepts the digits 0 through 9, plus the minus sign (only at the beginning) and/or decimal point (only one per field) if specified.

This solve the problem about the many '.' in EditText

if anyone still finding proper way, note that its setRawInputType() not setInputType()

val digits = "ABCDabcd" // or any characters you want to allow
editText.keyListener = DigitsKeyListener.getInstance(digits)
editText.setRawInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME)

None of the above solutions worked as expected. Digits in xml file still allow me to put "," in the input. Check for it, it's works for me:

edittext.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);