背景:项目中应用到边菜单栏,开源项目SlidingMenu有点大,项目中用不到这么多东东.
功能:可以在上下左右四个方向上显示侧边栏
效果图(就截一个图,其它图放上去太多了,不太好):
关键性代码:
a.初始化时位置处理
/**
* 左边栏的属性初始化
*/
protected void menuLeftProperties() {
M_LAYOUT_POSITION = ISMENU_OPEN ? 0 : -MENU_WIDTH;
//当打开时,右边的移动。理解:保持画布不动,视图区移动
M_SLIDER_MAX_OPEN = ISMENU_OPEN ? 0 : -MENU_WIDTH;
//当移动时左边的移动
M_SLIDER_MAX_CLOSE = ISMENU_OPEN ? MENU_WIDTH : 0 ;
//偏移位置
mMovePosition = ISMENU_OPEN ? 0 : -MENU_WIDTH;
}
/**
* 右边栏的属性初始化
*/
protected void menuRightProperties() {
M_LAYOUT_POSITION = ISMENU_OPEN ? -MENU_WIDTH : 0;
//打开时
M_SLIDER_MAX_OPEN = ISMENU_OPEN ? 0 : MENU_WIDTH;
//关闭时
M_SLIDER_MAX_CLOSE = ISMENU_OPEN ? -MENU_WIDTH : 0;
//偏移位置
mMovePosition = ISMENU_OPEN ? 0 : MENU_WIDTH;
}
b.消息是否拦截
/**
* 判断是否需要处理事件
*
* @param ev
* @return
*/
protected boolean isInterceptTouchEvent(MotionEvent ev) {
boolean isIntercept = false;
switch (MENU_POSITION) {
case LEFT:
isIntercept = isInterceptMenuLeftTouchEvent(ev);
break;
case RIGHT:
isIntercept = isInterceptMenuRightTouchEvent(ev);
break;
case TOP:
isIntercept = isInterceptMenuTopTouchEvent(ev);
break;
case BOTTOM:
isIntercept = isInterceptMenuBottomTouchEvent(ev);
break;
}
return isIntercept;
}
/**
* 边栏左边是否要处理
* @param ev
* @return
*/
protected boolean isInterceptMenuLeftTouchEvent(MotionEvent ev) {
//是左右滑动
boolean isIntercept = Math.abs(ev.getY() - MOTIONEVENT_Y) <= Math.abs(ev.getX() - MOTIONEVENT_X);
return isIntercept && ((MOTIONEVENT_X >= 0 && MOTIONEVENT_X <= TOUCH_OPEN_MENU_DISTANCE
&& !ISMENU_OPEN && (ev.getX() - MOTIONEVENT_X) > 0)
|| (ev.getX() - MOTIONEVENT_X < 0 && ISMENU_OPEN));
}
c.菜单栏的移动
/**
* 当Menu菜单在左边时
* @param event
*/
protected void menuLeftMoveEvent(MotionEvent event) {
float distance = event.getX() - MOTIONEVENT_X;
//向右滑动,打开菜单栏
if(distance > 0) {
if(distance + mMovePosition >= 0) {
ISMENU_OPEN = true;
mMovePosition = 0;
smoothScrollTo(M_SLIDER_MAX_OPEN, 0);
return ;
}else {
mMovePosition += distance;
}
}else if(distance < 0) {
if(distance + mMovePosition <= -MENU_WIDTH) {
ISMENU_OPEN = false;
mMovePosition = -MENU_WIDTH;
smoothScrollTo(M_SLIDER_MAX_CLOSE, 0);
return ;
}else {
mMovePosition += distance;
}
}
smoothScrollBy((int) - distance, 0);
MOTIONEVENT_X = event.getX();
}
其它一些代码都做过相应的注释 整个工程在附件中.