[英]Edittext - How do I only allow one dot to be added?
This is my edittext这是我的编辑文本
<EditText
android:id="@+id/etWaardeVan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:digits="0123456789."
android:inputType="number|numberDecimal"
android:scrollHorizontally="true"
android:singleLine="true"
/>
How do I programmatically allow for only one dot to be input.我如何以编程方式只允许输入一个点。
Is this what you are looking for?这是您要找的吗?
Set EditText Digits Programmatically 以编程方式设置 EditText 数字
etWarDevan.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
I'd remove the last entered character if its a dot and there has been one before.如果最后一个输入的字符是一个点并且之前有一个,我会删除它。
EditText field = view.findViewById(R.id.etWaardeVan);
field.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable editable) {
String str = editable.toString();
String strold = str.substring(0, str.length() - 2);
String lastchar = str.substring(str.length() - 1);
if(strold.contains(".") && lastchar.equals(".")) field.setText(str);
}
});
Hint: this only works if the user doesn't jump back and enters the dot in the middle of the string.提示:这仅在用户不跳回并在字符串中间输入点时才有效。 You may want to disable cursor movement.
您可能想要禁用光标移动。 (Like this or using
android:cursorVisible
) (像这样或使用
android:cursorVisible
)
Alternatively (if the input always contains a dot) you can just create two EditTexts without a dot allowed.或者(如果输入始终包含一个点)您可以只创建两个 EditTexts 而不允许使用点。
Here is my solution, and it works:这是我的解决方案,它有效:
dot.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//only show one dot if user put more than one dot
if(input.contains(".")){
//then save what it has
input = textView.getText().toString();
}else {
//concat the input value
input=input+".";
}
}
});
Basically, EditText is derived from TextView which has a基本上, EditText派生自TextView ,它有一个
void addTextChangedListener(TextWatcher watcher)
method.方法。 TextWatcher has callbacks, like
TextWatcher有回调,比如
abstract void afterTextChanged(Editable s)
that you can implement in order to filter the new text to only contain period.您可以实施以过滤新文本以仅包含句点。
Regex: (?<=^| )\\d+(\\.\\d+)?(?=$| )
正则表达式:
(?<=^| )\\d+(\\.\\d+)?(?=$| )
Example例子
et1.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
// Do something here with regex pattern
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
将 EditText/TextInputEditText 中的 inputType 属性设置为android:inputType="numberDecimal"
Replace: android:inputType="number|numberDecimal"
替换:
android:inputType="number|numberDecimal"
With: android:inputType="number"
与:
android:inputType="number"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.