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

上一篇博客中讲过如何判断软键盘的弹出并隐藏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中,键盘弹出来,只要手指一触摸屏幕,键盘就能消失,并且不会触发子控件的触摸事件.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值