public class MyDrawer extends FrameLayout {
private LinearLayout content;
private LinearLayout menu;
private int width=400;
//系统存值
PointF pointF=new PointF();
int x;
int y;
public MyDrawer(Context context) {
super(context);
init();
}
public MyDrawer(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyDrawer(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
}
public void init(){
//主菜单
content=new LinearLayout(getContext());
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
content.setBackgroundColor(Color.GREEN);
content.setOrientation(LinearLayout.VERTICAL);
content.setLayoutParams(params);
//侧滑菜单
menu=new LinearLayout(getContext());
FrameLayout.LayoutParams pr = new FrameLayout.LayoutParams(width, ViewGroup.LayoutParams.MATCH_PARENT);
menu.setBackgroundColor(Color.RED);
menu.setOrientation(LinearLayout.VERTICAL);
pr.leftMargin-=width;
menu.setLayoutParams(pr);
addView(content);
addView(menu);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
pointF.x = event.getX();
pointF.y = event.getY();
break;
case MotionEvent.ACTION_MOVE:
moveDrawer(event);
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
private boolean moveDrawer(MotionEvent event){
if (Math.abs(pointF.x-event.getX())>5){
int x= (int) (event.getX()-pointF.x);
FrameLayout.LayoutParams layoutParams = (LayoutParams) menu.getLayoutParams();
int nowx=layoutParams.leftMargin;
layoutParams.leftMargin=nowx+x;
if (layoutParams.leftMargin>0){
layoutParams.leftMargin=0;
}
if (layoutParams.leftMargin<-width){
layoutParams.leftMargin=-width;
}
menu.requestLayout();
pointF.x=event.getX();
pointF.y=event.getY();
}
return true;
}
}