您的位置:首页 > 其它

使用DrawerLayout过程中主页面内容被遮住且不能点击的一小解决方案

2016-05-26 23:57 453 查看
前几天,公司一同事让我帮忙解决用DrawerLayout时,DrawerLayout的侧边栏有种像Dialog那样的遮罩效果,而且主页面内容点击不了,他要实现的功能是:去掉遮罩效果,并且主页面内容例如Button之类的能够点击,并且触发点击时,侧边栏不能自动关闭,另外还要有常用的可以滑动侧边栏关闭侧边栏,点击侧边栏的item要能够触发相应的事件的效果,于是就有了以下的博客

首先,去掉遮罩效果很好实现,网上一大堆解决方案,一般是通过设置如下代码实现:drawer.setDrawerListener(toggle);

其次,主页面内容不能点击,这个很容易就知道是主页面事件被拦截了,那么是在DrawerLayout的onInterceptTouchEvent里面处理事件拦截还是在onTouchEvent里面处理拦截事件呢?嗯,这个问题要想清楚,首先,借用鸿洋的话语,DrawerLayout和DrawerView以及ContentView的关系就像爸爸和两个儿子,如果在onTouchEvent处理拦截事件,判断isDrawerOpen并且点击位置位于ContentView里面,那样的话就会导致钱被爸爸拿去了,大哥ContentView拿不到钱,那肯定不行,现在大哥要能触发事件,要拿到钱,所以要在爸爸将要把钱拿去的时候拿到钱才行,所以,最终要在onInterceptTouchEvent里面处理事件,我是通过自定义DrawerLayout来实现的,重要代码如下:

@Override
public boolean onInterceptTouchEvent(MotionEvent ev){
switch(ev.getAction()) {
case MotionEvent.ACTION_DOWN:
final float x = ev.getX();
final float y = ev.getY();
final View touchedView = findTopChildUnder((int) x, (int) y);
if (touchedView != null && isContentView(touchedView)
&& this.isDrawerOpen(GravityCompat.START)) {
return false;
}
break;

default:
break;
}
return super.onInterceptTouchEvent(ev);
}

/**
* 判断点击位置是否位于相应的View内
* @param x
* @param y
* @return
*/
public View findTopChildUnder(int x, int y) {
final int childCount = getChildCount();
for (int i = childCount - 1; i >= 0; i--) {
final View child = getChildAt(i);
if (x >= child.getLeft() && x < child.getRight() &&
y >= child.getTop() && y < child.getBottom()) {
return child;
}
}
return null;
}

/**
* 判断点击触摸点的View是否是ContentView(即是主页面的View)
* @param child
* @return
*/
boolean isContentView(View child) {
return ((LayoutParams) child.getLayoutParams()).gravity == Gravity.NO_GRAVITY;
}


嗯,就是以上代码就实现了同事想实现的效果了。最后感谢鸿洋给予的帮助!

最后附上源码下载链接:点我下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  DrawerLayo