Android--侧滑菜单
效果:
---向右滑动-->
实现:
自定义view:
public class LeftMenuView extends HorizontalScrollView { /**定义横向滚动条布局*/ private LinearLayout mScrollView; /**定义菜单区域*/ private ViewGroup mMenu; /**定义主显示区域*/ private ViewGroup mContent; /**定义屏幕宽度*/ private int mScreenWidth; /**定义菜单右边距为50dp*/ private int mMenuRightPadding = 50; /**定义只设置一次自己和子视图的宽和高*/ private boolean call; /**定义菜单宽度*/ private int mMenuWidth; /** * 构造方法 * 初始化数据 * */ public LeftMenuView(Context context, AttributeSet attrs) { super(context, attrs); //获取窗口管理器服务 WindowManager wm= (WindowManager) context.getSystemService(context.WINDOW_SERVICE); //创建显示尺寸对象 DisplayMetrics dm=new DisplayMetrics(); //获取当前屏幕的宽高尺寸 wm.getDefaultDisplay().getMetrics(dm); //为屏幕宽度赋值 mScreenWidth=dm.widthPixels; //将50dp边距转为像素值px mMenuRightPadding= (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,50, context.getResources().getDisplayMetrics()); //隐藏滚动条 this.setHorizontalScrollBarEnabled(false); } /** * 设置滚动视图与子视图的宽和高 * */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //用于判断只设置一次尺寸 if (!call){ //获取滚动视图中的子布局 mScrollView = (LinearLayout) getChildAt(0); //获取菜单区域 mMenu = (ViewGroup) mScrollView.getChildAt(0); //获取主显示区域 mContent = (ViewGroup) mScrollView.getChildAt(1); //设置菜单宽度 mMenuWidth = mMenu.getLayoutParams().width = mScreenWidth - mMenuRightPadding; //设置主显示区域宽度 mContent.getLayoutParams().width = mScreenWidth; call = true; } 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(mMenuWidth, 0); } } }
main.xml:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--自定义横向滚动条--> <com.example.shanshan.leftmenu.LeftMenuView android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="horizontal"> <include layout="@layout/left_menu" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/colorPrimaryDark"> </LinearLayout> </LinearLayout> </com.example.shanshan.leftmenu.LeftMenuView> </RelativeLayout>