如何在Android上设计一个这样的EditText:用户不用使用回车或换行符输入一个多行文本,但是文本显示依然是多行,即有自动换行。
类似于内置的SMS应用程序,我们不需要输入换行符但文本是多行显示的。
你说的sms中的效果实现代码是这个,可以参考下,要实现 TextView.OnEditorActionListener这个接口,机关就在这个方法里,具体也可参考 Mms源码 composeMessageActivity.java
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (event != null) {
// if shift key is down, then we want to insert the '\n' char in the TextView;
// otherwise, the default action is to send the message.
if (!event.isShiftPressed()) {
if (isPreparedForSending()) {
//confirmSendMessageIfNeeded();
showDialog(SIM_CARD_CHOOSER_ID, null);
}
return true;
}
return false;
}
试试这段代码:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER)
{
//Nothing
return true;
}
return super.onKeyDown(keyCode, event);
}
class MyTextView extends EditText
{
...
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode==KeyEvent.KEYCODE_ENTER)
{
// Just ignore the [Enter] key
return true;
}
// Handle all other keys in the default way
return super.onKeyDown(keyCode, event);
}
}
使用以下这个方法你不用重写 EditText类。只需要使用空字符串捕捉然后替代换行符。
myEditTextObject.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
for(int i = s.length(); i > 0; i--){
if(s.subSequence(i-1, i).toString().equals("\n"))
s.replace(i-1, i, "");
}
}
});