问题
My Use case is to restrict user after he has entered 4 lines in text box. Setting maxLines
will not work to stop user.
I am surprise that Android is not providing key down/up event when input type is InputType.TYPE_CLASS_TEXT
. I am receiving event for all other types. Below is my code.
EditText et = new EditText(this);
et.setMaxLines(3);
et.setSingleLine(false);
et.setInputType(InputType.TYPE_CLASS_TEXT);
et.setHint("First edit text");
et.setKeyListener(this); // This key listener is also not working.
et.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.d("MainActivity.class", "event received"); // This event is never called.
return false;
}
});
@Override
public int getInputType() {
return InputType.TYPE_CLASS_NUMBER;
}
@Override
public boolean onKeyDown(View view, Editable text, int keyCode, KeyEvent event) { // THIS EVENT HITS ONLY WHEN INPUT TYPE IS OTHER THAN TEXT.
return false;
}
@Override
public boolean onKeyUp(View view, Editable text, int keyCode, KeyEvent event) {
return false;
}
@Override
public boolean onKeyOther(View view, Editable text, KeyEvent event) {
return false;
}
@Override
public void clearMetaKeyState(View view, Editable content, int states) {
}
even onKeyDown()
of activity is also not working.
When I am setting InputType.TYPE_CLASS_NUMBER
or InputType.TYPE_CLASS_PHONE
, it is working fine.
P.S. I want to get key down ewvent for Input Type Text.
回答1:
Not exactly what you asked but this is another way to accomplish it.
You can add a textChangedListener to your EditText.
editText.addTextChangedListener(new TextWatcher() {
String text;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if(editText.getLineCount()==2)
{
text=s.toString();
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if(editText.getLineCount()>2)
{
editText.setText(text);
editText.setSelection(text.length()); //move cursor to the end of the string
}
}
});
回答2:
You can directly check lines entered in EditText.
int lineCount = et.getLineCount();
lineCount
variable will return how much lines of text in EditText.
only issue is it is returning 1 without entering anything in EditText.
-> If you want to handle Enter key event and restrict user to enter another line:
et.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
if(et.getLineCount() <= 3) {
Toast.makeText(mContext, "Text =" + et.getText()+ ", and lines = " + et.getLineCount(), Toast.LENGTH_SHORT).show();
return false;
} else {
Toast.makeText(mContext, "Only four lines permitted...", Toast.LENGTH_SHORT).show();
return true;
}
}
return false;
}
});
来源:https://stackoverflow.com/questions/53498009/handle-edittext-key-change-event-with-input-type-text