我有一个编辑Text.I不希望第一个字母是空格。 如果用户点击空格,则第一个字母光标不应移动。
答案 0 :(得分:9)
像这样创建一个TextWatcher
public class MyTextWatcher implements TextWatcher {
private EditText editText;
public MyTextWatcher(EditText editText) {
this.editText = editText;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String text = editText.getText().toString();
if (text.startsWith(" ")) {
editText.setText(text.trim());
}
}
@Override
public void afterTextChanged(Editable s) {
}
}
并将其添加到EditText
editText.addTextChangedListener(new MyTextWatcher(editText));
答案 1 :(得分:2)
基于卢卡的第一个答案:
TextWatcher mWatcher = new TextWatcher() {
@Override public void afterTextChanged(Editable editable) {
if (myEditText.getText().toString().startsWith(" "))
myEditText.setText("");
}
我将equals
更改为startsWith
比设定
答案 2 :(得分:0)
var myApp = angular.module('myApp', []);
myApp.controller('mainCtrl', function($scope){
$scope.countryList = [
{
id: null,
name: 'Please Select',
states: [
{name: 'Please Select', stateid: null}
]
},
{
id: 1,
name: 'United States of America',
states: [
{name: 'Alabama', stateid: 1},
{name: 'Alaska', stateid: 2},
{name: 'Arizona', stateid: 3}
]
},
{
id: 2,
name: 'Australia',
states: [
{name: 'Australian Capital Territory', stateid: 1},
{name: 'New South Wales', stateid: 2},
{name: 'Northern Territory', stateid: 3}
]
},
];
$scope.stateList = $scope.countryList[0].states;
})
然后
TextWatcher myWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
if (myEditText.getText().toString().equals(" "))
myEditText.setText("");
}
答案 3 :(得分:0)
您可以按照以下方法将InputFilter
设置为Edittext
。它会限制用户在开始时输入空间。
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
if (source.length()>0 &&Character.isWhitespace(source.charAt(0)) && yourEditText.getText().toString().length()==0) {
return "";
}
return source;
}
};
yourEditText.setFilters(new InputFilter[] { filter });
与此方案中的InputFilter
相比,
TextWatcher
在性能方面更可靠。您可以参考https://stackoverflow.com/a/33855940/3817374获取更详细的信息。
答案 4 :(得分:-1)
添加if else条件以检查第一个字母
if(EditText.getText().charAt(0)!=" "){
//COOL!
}
else
{
//ERROR!
}
确保它在ui线程上运行