Fragment如何调用所在Activity的dispatchTouchEvent(MotionEvent ev)函数
2015-10-14 20:06
246 查看
上一篇博客中讲过如何判断软键盘的弹出并隐藏,其中hideKeyboard()函数放在Activity的dispatchTouchEvent(MotionEvent ev)函数中就可以完美地使用:
也就是说,如果Activity接受到down事件,就执行hideKeyboard(),并且如果返回true,也就是说键盘已经弹出并隐藏,此时返回false,不再把触摸时间分发给子控件.但是如果在Fragment中,该如何使用父Activity的dispatchTouchEvent函数呢?
第一想到接口,在父Activity中定义一个接口
接着再定义设置接口函数
当然,要先在Activity中加上
在Fragment中覆写onAttach函数
最后,在Acitivity中覆写dispatchTouchEvent(MotionEvent)函数
这样,在Fragment中,键盘弹出来,只要手指一触摸屏幕,键盘就能消失,并且不会触发子控件的触摸事件.
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中,键盘弹出来,只要手指一触摸屏幕,键盘就能消失,并且不会触发子控件的触摸事件.
相关文章推荐
- 面试70问 经典回答
- Android Studio 插件之内存泄露检测LeakCanary使用
- c语言几个点
- try throw catch typeid
- ~~~
- (转)面试70问 经典回答
- ARP
- 【机器学习】先验概率、后验概率、贝叶斯公式、 似然函数
- 八大排序算法
- 倒置链表(递归方式)
- 如何写好博客
- [转帖]vivado & VS2013工具
- objective-c制作汤姆猫
- PostgreSQL security usage guide
- Linux下Apache重启遇到No space left on device错误的解决方法
- Response实现验证码功能
- 文章标题
- 【开篇.流水账.反思】从今天开始记录我的学习生涯
- PostgreSQL function's SECURITY DEFINER | INVOKER, SET configuration_parameter { TO value | = value |
- 数字流的使用