上一篇博客中講過如何判斷軟鍵盤的彈出並隱藏http://www.cnblogs.com/thare1307/p/4617558.html
其中hideKeyboard()函數放在Activity的dispatchTouchEvent(MotionEvent ev)函數中就可以完美地使用
public boolean dispatchTouchEvent(MotionEvent ev) { // TODO Auto-generated method stub if(ev.getAction()==MotionEvent.ACTION_DOWN) if(hideKeyboard()) return false; return super.dispatchTouchEvent(ev); }
也就是說,如果Activity接受到down事件,就執行hideKeyboard(),並且如果返回true,也就是說鍵盤已經彈出並隱藏,此時返回false,不再把觸摸時間分發給子控件.但是如果在Fragment中,該如何使用父Activity的dispatchTouchEvent函數呢?
第一想到接口.
在父Activity中定義一個接口
public interface OnHideKeyboardListener{ public boolean hideKeyboard(); }
接着再定義設置接口函數
public void setOnHideKeyboardListener(OnHideKeyboardListener onHideKeyboardListener){ this.onHideKeyboardListener = onHideKeyboardListener; }
當然,要先在Activity中加上
private OnHideKeyboardListener onHideKeyboardListener;
在Fragment中覆寫onAttach函數
public void onAttach(Activity activity) { // TODO Auto-generated method stub OnHideKeyboardListener onHideKeyboardListener = new OnHideKeyboardListener() { @Override public boolean hideKeyboard() { // TODO Auto-generated method stub if(inputMethodManager.isActive(searchEditText)){ getView().requestFocus();
inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().
getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); return true; } return false; } }; ((TabFragment)getActivity()).setOnHideKeyboardListener(onHideKeyboardListener); super.onAttach(activity); }
最后,在Acitivity中覆寫dispatchTouchEvent(MotionEvent)函數
public boolean dispatchTouchEvent(MotionEvent ev) { // TODO Auto-generated method stub if(onHideKeyboardListener != null){ if(ev.getAction() == MotionEvent.ACTION_DOWN){ if(onHideKeyboardListener.hideKeyboard()){ return false; //不在分發觸控給子控件 } } } return super.dispatchTouchEvent(ev); }
這樣,在Fragment中,鍵盤彈出來,只要手指一觸摸屏幕,鍵盤就能消失,並且不會觸發子控件的觸摸事件.