Set EditText Digits Programmatically

2019-01-08 12:05发布

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?

4条回答
淡お忘
2楼-- · 2019-01-08 12:25

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" />
查看更多
孤傲高冷的网名
3楼-- · 2019-01-08 12:31

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

查看更多
爷的心禁止访问
4楼-- · 2019-01-08 12:40

Use InputType.TYPE_NUMBER_FLAG_DECIMAL.

Also see: Input Types.

查看更多
祖国的老花朵
5楼-- · 2019-01-08 12:49

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.

查看更多
登录 后发表回答