- 侧滑菜单
- 代码实现步骤
- [1]先画主页面 代码如下
-
- [2]画菜单页面
-
- [3]把共同的属性抽到一个style里面
-
- [4] 通过include 把2个孩子加入到main_activity页面
-
- [5]对孩子重新排版 重写onlayout方法
@Override protected void onLayout(boolean changed, int l, int t, int r, int b) { View main = getChildAt(0); View child = getChildAt(1); width = child.getMeasuredWidth(); child.layout(-width, t, l, b); main.layout(l, t, r, b); }
-
- [6]让容器消费事件,就是重写onTouchEvent方法 处理手指按下 和移动的逻辑
@Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: downX = event.getX(); break; case MotionEvent.ACTION_MOVE: float moveX = event.getX(); distanceX = moveX - downX + currentLeft; if (distanceX <= 0) { distanceX = 0; } else if (distanceX >= width) { distanceX = width; } scrollToX((int) distanceX); break; case MotionEvent.ACTION_UP: if (distanceX >= width / 2) { currentLeft = width; } else { currentLeft = 0; } float startX = distanceX; float endX = currentLeft; startToend(startX, endX); break; } return true; }
-
- [7]处理手指抬起的逻辑
case MotionEvent.ACTION_UP: if (distanceX >= width / 2) { currentLeft = width; } else { currentLeft = 0; } float startX = distanceX; float endX = currentLeft; startToend(startX, endX); break;
-
- [8]让view 实现平滑滚动. Scroller
- [8.1]先获取scroller实例
- [8]让view 实现平滑滚动. Scroller
scroller = new Scroller(getContext());
-
-
- [8.2] 模拟X轴滚动的数据
-
private void startToend(float startX, float endX) { int sx = (int) startX; int dx = (int) (endX - startX); int time = dx * 15; scroller.startScroll(sx, 0, dx, 0, time); invalidate(); }
-
-
- [8.3] 取出模拟的数据
-
@Override public void computeScroll() { if (scroller.computeScrollOffset()) { int currX = scroller.getCurrX(); scrollToX(currX); invalidate(); } }
-
- [9].点击按钮实现菜单切换
public void switchMenu() { int startX = 0; if (currentLeft == 0) { currentLeft = width; startX = 0; } else { currentLeft = 0; startX = width; } startToend(startX, currentLeft); }
-
- [10].处理事件冲突. 如果x轴移动的距离 > Y轴移动的距离就拦截事件
@Override public boolean onInterceptHoverEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: downX = event.getX(); downY = event.getY(); break; case MotionEvent.ACTION_MOVE: float moveX = event.getX(); float moveY = event.getY(); float distanceX = moveX - downX; float distanceY = moveY - downY; if (Math.abs(distanceX) > Math.abs(distanceY)) { return true; } break; case MotionEvent.ACTION_UP: break; } return false; }
https://github.com/nangongyibin7219/Android_SlidingMenu