仿QQ侧滑菜单(一)
很多著名的APP 里面都会有一个侧滑菜单,所以我们来做一个类似QQ的侧滑菜单。
首先我们会用到Drawerlayout和navigationView。我们一个个来学习。
Drawerlayout是第三方控件SlidingMenu之后的google借鉴的产物。Drawerlayout是一个布局控件,就好像我们常见的Linearlayout、Relativelayout一样的布局。他分为两侧布局和中间的主布局,可以通过手势将其打开或者关闭。
在写布局的时候我们需要通过对Drawerlayout中的子布局进行layout_gravity的定义来区分左右中布局(left、right、无)。
可以看出,他是分左右的。
其实只要在acitivity_main.XML里面写好布局就可以出现抽屉效果了,只是如果需要更复杂的装填的话需要容器的配合,下面给大家看一下XML文件,这个拷贝过去就可以直接出来效果了:
<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <LinearLayout android:id="@+id/menu" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/menu_text" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal|center_vertical" android:text="hello world" /> </LinearLayout> <LinearLayout android:id="@+id/left_layout" android:layout_width="320dp" android:layout_height="match_parent" android:layout_gravity="left" android:background="@color/myQQMenuColor" android:orientation="vertical"> <ListView android:id="@+id/left_list" android:layout_marginTop="5dp" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> </ListView> <!-- 在布局文件中不可以直接添加listview中的item, 否则会报错:java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView 需要在.java文件中对list的元素一个个添加,并且用适配器将其匹配起来 --> <ListView android:id="@+id/left_btn_list" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> </ListView> </LinearLayout> </android.support.v4.widget.DrawerLayout>