軟鍵盤顯示和隱藏的監聽:
注: mReplayRelativeLayout是EditText的父布局
//監聽軟鍵盤是否顯示或隱藏 mReplayRelativeLayout.getViewTreeObserver().addOnGlobalLayoutListener( new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Rect r = new Rect(); mReplayRelativeLayout.getWindowVisibleDisplayFrame(r); int screenHeight = mReplayRelativeLayout.getRootView() .getHeight(); int heightDifference = screenHeight - (r.bottom); if (heightDifference > 200) { //軟鍵盤顯示 // changeKeyboardHeight(heightDifference); } else { //軟鍵盤隱藏 } } });
點擊一個控件使EditText獲取焦點並彈出軟鍵盤:
在該控件的點擊事件中寫以下代碼:
mEditText.setFocusable(true); mEditText.setFocusableInTouchMode(true); mEditText.requestFocus(); mEditText.findFocus(); InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(mEditText, InputMethodManager.SHOW_FORCED);// 顯示輸入法
軟鍵盤的隱藏方法一:
注:該方法其實是如果軟鍵盤隱藏的狀態這打開軟鍵盤,反之着相反。
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
軟鍵盤的隱藏方法二:
注:推薦使用這個
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
EditText讓其在剛進頁面的時候不被選中(不處於焦點狀態):
解決辦法:
在EditText的父布局的xml文件中把焦點占據,寫一下代碼:
android:focusable="true"
android:focusableInTouchMode="true"
注:點擊EditText后使其獲取焦點並彈出軟件盤,推薦使用setOnTouchListener監聽:
mReplayEditText.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { mReplayEditText.setFocusable(true); mReplayEditText.setFocusableInTouchMode(true); return false; } });