Set EditText Digits Programmatically

2019-01-08 11:47发布

问题:

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?

回答1:

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.



回答2:

Try this:

weightInput.setInputType(InputType.TYPE_CLASS_NUMBER);          
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



回答3:

Use InputType.TYPE_NUMBER_FLAG_DECIMAL.

Also see: Input Types.



回答4:

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