2025-04-22

"EditText + Button" 形成一個"輸入+按鍵響應" 的案例在android編程中是最常見不過的瞭。
 
但還有一些細節需要註意:
 
在EditText輸入後,點擊Button進行請求,軟鍵盤應該自行消失
在EditText輸入後,不點擊Button進行請求,而是直接點擊軟鍵盤上的"回車",那麼也應該能夠正常響應請求
針對問題1,可以在響應Button的onClick事件中,主動將軟鍵盤隱藏,加入如下代碼即可
[java]
InputMethodManager imm =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0); 
針對問題2,可以在EditText的api doc中找到答案
void android.widget.TextView.setOnEditorActionListener(OnEditorActionListener l)
Set a special listener to be called when an action is performed on the text view. This will be called when the enter key is pressed, or when an action supplied to the IME is selected by the user. Setting this means that the normal hard key event will not insert a newline into the text view, even if it is multi-line; holding down the ALT modifier will, however, allow the user to insert a newline character.
 
Parameters:
l
因此,隻需要給EditText設置一個onEditorActionListener就好瞭,簡單示例如下
[java]  www.aiwalls.com
// The action listener for the EditText widget, to listen for the return key 
private TextView.OnEditorActionListener mWriteListener = 
    new TextView.OnEditorActionListener() { 
    public boolean onEditorAction(TextView view, int actionId, KeyEvent event) { 
        // If the action is a key-up event on the return key, send the message 
        if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) { 
            String message = view.getText().toString(); 
            sendMessage(message); 
        } 
        if(D) Log.i(TAG, "END onEditorAction"); 
        return true; 
    } 
}; 
備註一下:TextView.OnEditorActionListener接口方法onEditorAction方法的第二個參數actionId,其可能的值在EditorInfo的說明中能夠找到。列舉如下

IME_ACTION_DONE
IME_ACTION_GO
IME_ACTION_NEXT
IME_ACTION_NONE
IME_ACTION_PREVIOUS
IME_ACTION_SEARCH
IME_ACTION_SEND
IME_ACTION_UNSPECIFIED 

摘自 火山哥的專欄

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *