EditText是個基礎元件,基本預設按下去就會彈出鍵盤來讓你輸入內容,算是相當人性化,在部份情況下可能只要需要使用"EditText.getText()"來取出文字判斷就好,但在需要即時(如鍵盤按下瞬間就進行判斷)就需要用上其他方式
Listening soft keyboard 檢查軟體鍵盤(就是畫面彈出那個)
EditText.addTextChangedListener(new TextWatcher(){
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
System.out.println("afterTextChanged || 按下後");
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
System.out.println("beforeTextChanged || 按下前");
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
System.out.println("onTextChanged || 按下中");
}
});
但是光這樣還是有些鍵是檢查不到的 EX:ENTER(keyCode = 66)、BACKSPACE(keyCode = 67),必須再搭配下面這方式,下面這方是也可以偵測到外接鍵盤(可能對tablet比較常用)
EditText.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
System.out.println("keyCode = "+keyCode);
//return true = finish || false = track
return false;
}
});
如果只是要得到硬體鍵盤、按鍵,可以使用下面這方式
/* hardware keyboard */
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
//todo something
System.out.println("keyCode = "+keyCode+" || keyEvent = "+event);
//ex: ENTER
if(keyCode == KeyEvent.KEYCODE_ENTER){
//press ENTER
}
return super.onKeyDown(keyCode, event);
}
那如果都是使用外接鍵盤覺得內建鍵盤很礙眼就是要把他隱藏起來
//先宣告
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//隱藏起來 soft keyboard
inputManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
//叫出鍵盤 soft keyboard
inputManager.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
相關連結
Android Developers
Android Developers - InputMethodManager
Android Developers - TextWatcher
Android Developers - EditText
Android EditText Listening soft keyboard
by Isken Huang - 11/17/2010 - Android
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言