Fragment如何调用所在Activity的dispatchTouchEvent(MotionEvent ev)函数

来源:互联网 发布:御龙在天淘宝商城 编辑:程序博客网 时间:2024/05/23 01:18
上一篇博客中讲过如何判断软键盘的弹出并隐藏http://www.cnblogs.com/thare1307/p/4617558.html

  其中hideKeyboard()函数放在Activity的dispatchTouchEvent(MotionEvent ev)函数中就可以完美地使用

  

public boolean dispatchTouchEvent(MotionEvent ev) {// TODO Auto-generated method stubif(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 stubOnHideKeyboardListener onHideKeyboardListener = new OnHideKeyboardListener() {@Overridepublic boolean hideKeyboard() {// TODO Auto-generated method stubif(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 stubif(onHideKeyboardListener != null){if(ev.getAction() == MotionEvent.ACTION_DOWN){if(onHideKeyboardListener.hideKeyboard()){return false;  //不在分发触控给子控件}}}return super.dispatchTouchEvent(ev);}

   这样,在Fragment中,键盘弹出来,只要手指一触摸屏幕,键盘就能消失,并且不会触发子控件的触摸事件.

0 0
原创粉丝点击