效果如图所示:
1.实现左侧menu布局
2.实现主布局
3.将左侧menu布局加入到主布局中去
4.编写自定义ViewGroup
部分代码实现:
1.menu布局代码
略
2.主布局代码
略
3.相结合代码
<包名.SlidingMenu
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
//menu布局
<include layout="@layout/leftmenu" />
//主布局内容
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
</包名.SlidingMenu>
4.自定义的ViewGroup实现
import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
public class SlidingMenu extends HorizontalScrollView {
private LinearLayout mLinearLayout;
private ViewGroup mMenu;
private ViewGroup mContent;
private int mScreenWidth;
private int mMenuWidth;
// dp
private int mMenuRightPadding = 200;
private boolean once = false;
// 未使用自定义属性时,调用
public SlidingMenu(Context context, AttributeSet attrs) {
super(context, attrs);
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
mScreenWidth = outMetrics.widthPixels;
// 把dp转化为px
mMenuRightPadding = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 200, context.getResources()
.getDisplayMetrics());
}
// 设置子View的宽和高
// 设置自己的宽和高
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (!once) {
mLinearLayout = (LinearLayout) getChildAt(0);
mMenu = (ViewGroup) mLinearLayout.getChildAt(0);
mContent = (ViewGroup) mLinearLayout.getChildAt(1);
mMenuWidth = mMenu.getLayoutParams().width = mScreenWidth
- mMenuRightPadding;
mContent.getLayoutParams().width = mScreenWidth;
once = true;
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
// 通过设置偏移量,将menu隐藏
@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(mMenuWidth, 0);
}
}
// 手指抬起时
@Override
public boolean onTouchEvent(MotionEvent ev) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_UP:
// 隐藏在左边的宽度
int scrollx = getScrollX();
if (scrollx >= mMenuWidth / 2) {
this.smoothScrollTo(mMenuWidth, 0);
} else {
this.smoothScrollTo(0, 0);
}
return true;
}
return super.onTouchEvent(ev);
}
}