android軟鍵盤的一些控制

"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中找到答案
public void setOnEditorActionListener (TextView.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.
因此,只需要給EditText設置一個onEditorActionListener就好了,簡單示例如下
	mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
		@Override
		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
			//TODO 這裏做"回車"響應處理
			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





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章