我想在edittext中有5行,所以用户只能按Enter
4次,我试过这样但仍然无法工作
myEtidtext.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
// if enter is pressed start calculating
if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
// get EditText text
String text = ((EditText) v).getText().toString();
// find how many rows it cointains
int editTextRowCount = text.split("\\n").length;
// user has input more than limited - lets do something
// about that
if (editTextRowCount >= 5) {
// find the last break
int lastBreakIndex = text.lastIndexOf("\n");
// compose new text
String newText = text.substring(0, lastBreakIndex);
// add new text - delete old one and append new one
// (append because I want the cursor to be at the end)
((EditText) v).setText("");
((EditText) v).append(newText);
}
}
return false;
}
});