Android軟鍵盤的一些控制

來源:互聯網
上載者:User

"EditText + Button" 形成一個 "輸入+按鍵響應" 的案例在android編程中是最常見不過的了。

但還有一些細節需要注意:

  1. 在EditText輸入後,點擊Button進行請求,軟鍵盤應該自行消失
  2. 在EditText輸入後,不點擊Button進行請求,而是直接點擊軟鍵盤上的"斷行符號",那麼也應該能夠正常響應請求
針對問題1,可以在響應Button的onClick事件中,主動將軟鍵盤隱藏,加入如下代碼即可
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就好了,簡單樣本如下

    // 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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.