您的位置:首页 > 其它

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

2015-07-16 10:17 701 查看
  上一篇博客中讲过如何判断软键盘的弹出并隐藏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中,键盘弹出来,只要手指一触摸屏幕,键盘就能消失,并且不会触发子控件的触摸事件.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: