我也不说废话了,和上一个左滑差不多一样,我就贴一下主要代码,
有什么问题请留言哈,
import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
public class LeftMenu extends HorizontalScrollView {
Context context;
int width;// 屏幕的宽度
int left_width;// leftmenu宽度
int right_width;// leftmenu宽度
int scrolWidth;// 滚动的宽度
boolean isleftOpen = false;// 判断侧滑菜单是否显示
boolean isrightOpen = false;
public LeftMenu(Context context) {
super(context);
this.context = context;
}
public LeftMenu(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
public LeftMenu(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
}
// 设置空间的大小
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 获取屏幕的宽度
WindowManager wm = (WindowManager) context
.getSystemService(context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
width = outMetrics.widthPixels;
left_width = (int) (width * 0.8);
scrolWidth = (int) (left_width / 2);
LinearLayout wrapper = (LinearLayout) getChildAt(0);
ViewGroup leftmenu = (ViewGroup) wrapper.getChildAt(0);
ViewGroup content = (ViewGroup) wrapper.getChildAt(1);
ViewGroup rightmenu = (ViewGroup) wrapper.getChildAt(2);
leftmenu.getLayoutParams().width = left_width;// 设置leftmenu的宽度
content.getLayoutParams().width = width;// 设置正文的宽度
rightmenu.getLayoutParams().width = left_width;// 设置leftmenu的宽度
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
// 设置控件的显示
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
if (changed) {
this.scrollTo(left_width, 0);// 隐藏leftmenu
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_UP:
int scrollX = getScrollX();
if (scrollX > scrolWidth + width) {//判断是左滑还是右滑
if (scrollX >= scrolWidth + left_width) {
this.smoothScrollTo(width + left_width, 0);
isrightOpen = true;
} else {
this.smoothScrollTo(left_width, 0);
isrightOpen = false;
}
} else {
// 如果显示区域大于菜单宽度一半则完全显示,否则隐藏
if (scrollX >= scrolWidth) {
this.smoothScrollTo(left_width, 0);
isleftOpen = false;
} else {
this.smoothScrollTo(0, 0);
isleftOpen = true;
}
}
break;
}
return super.onTouchEvent(ev);
}
// 判断leftmenu的显示隐藏,主要用于外部按钮的设置menu的显示隐藏
public void openMenu() {
if (isleftOpen) {
this.smoothScrollTo(left_width, 0);
isleftOpen = false;
} else {
this.smoothScrollTo(0, 0);
isleftOpen = true;
}
}
// 判断rightmenu的显示隐藏,主要用于外部按钮的设置menu的显示隐藏
public void openRightMenu() {
if (isrightOpen) {
this.smoothScrollTo(left_width, 0);
isrightOpen = false;
} else {
this.smoothScrollTo(width + left_width, 0);
isrightOpen = true;
}
}
}