Set EditText Digits Programmatically

AndroidAndroid Edittext

Android Problem Overview


I am essentially trying to set the digits value of an EditText programmatically. So far I have:

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

Which is fine, but I also want to be able to include a decimal place (.). Any ideas?

Android Solutions


Solution 1 - Android

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.

Solution 2 - Android

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

Solution 3 - Android

Use InputType.TYPE_NUMBER_FLAG_DECIMAL.

Also see: Input Types.

Solution 4 - Android

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)

Solution 5 - Android

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" />

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionryandlfView Question on Stackoverflow
Solution 1 - AndroidWhilerView Answer on Stackoverflow
Solution 2 - AndroidJoeyRAView Answer on Stackoverflow
Solution 3 - AndroidRickyView Answer on Stackoverflow
Solution 4 - AndroidAsadView Answer on Stackoverflow
Solution 5 - AndroidNAGESH M HView Answer on Stackoverflow