實作 TextView.OnEditorActionListener,在 onEditorAction 中判斷 event.isShiftPressed() 決定是否換行或執行發送動作,模擬簡訊應用行為。
editText.setOnEditorActionListener((v, actionId, event) -> {
if (event != null && event.getAction() == KeyEvent.ACTION_DOWN) {
if (!event.isShiftPressed()) {
// 未按 Shift + Enter:執行發送或完成動作
sendMessage();
return true; // 消費事件,不換行
}
// 按 Shift + Enter:允許換行(預設行為)
return false;
}
return false;
});
<EditText
android:inputType="textMultiLine"
android:imeOptions="actionSend"
android:maxLines="4"
... />
inputType="textMultiLine" 允許顯示多行。imeOptions="actionSend" 讓鍵盤顯示「發送」鍵。Enter 鍵,僅 Shift+Enter 產生換行符。