如何强制在EditText中显示不能删除但单击Backspace的字母。 恩。 [#____________] 在上面的示例中,#是该edittext字段的默认值。使用Edittext.gettext()时,它应该返回'#32343'
答案 0 :(得分:1)
立即想到几种方式,但我确实对你的问题感到困惑。看起来你想要(而不是显示一个空的EditText)显示一个带有开头字母的EditText。如果是这样的话,试试这个:
final EditText et = (EditText) findViewById(R.id.my_edit_text);
// default characters to display
// replace "#" with whatever you like
final String defaultTextDisplayed = "#";
// text is either set here or via xml, preferably via strings.xml
et.setText(defaultTextDisplayed);
et.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// ignored
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// ignored
}
// This is the callback we're interested in. Any time
// your user edits what is in the EditText, this method
// is called. We'll use it listen for when a user tries
// to delete the default display text.
@Override
public void afterTextChanged(Editable s) {
// if the user attempts to delete and of the default
// string displayed, just put it back
if (s.length() < defaultTextDisplayed.length()) {
et.setText(defaultTextDisplayed);
}
}
});
答案 1 :(得分:0)
您可以实施TextChangedListener
,确保文本的某些部分不会被删除/覆盖。
试试此代码
final EditText edt = (EditText) findViewById(R.id.editText1);
edt.setText("#");
Selection.setSelection(edt.getText(), edt.getText().length());
edt.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
if(!s.toString().contains("#")){
edt.setText("#");
Selection.setSelection(edt.getText(), edt.getText().length());
}
}
});