EditText 監聽 ENTER 鍵

方法1

//監聽Enter
editText.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if ((keyEvent.getAction() == KeyEvent.ACTION_UP) && (i == KeyEvent.KEYCODE_ENTER)) {
        //todo
        }
        return false;
    }
});

============
方法2 可排除因中文輸入法帶入兩次Enter

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        //當actionId == XX_SEND 或者 XX_DONE時都觸發
        //或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN時也觸發
        //注意,這是一定要判斷event != null。因為在某些輸入法上會返回null。
        if (actionId == EditorInfo.IME_ACTION_SEND
                || actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT
                || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
           //todo
        }
        return false;
    }
});