DrawerLayout是什么?
DrawerLayout是一个顶层窗体容器,允许可交互的抽屉组件从屏幕一侧拉出
DrawerLayout基本用法
1布局DrawerLayout的第一个子view作为内容视图组件需要指定高度为matchparent并且无layoutgravity属性。
2第二个子view作为抽屉组件需要通过layoutgravity指定方向高度matchparent和固定的宽度
代码示例
MainActivitypublic class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private Toolbar mToolBar;
private LinearLayout mContentLl;
private LinearLayout mDrawerLl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getViews();
setViews();
setListeners();
}
private void getViews() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
mContentLl = (LinearLayout) findViewById(R.id.ll_content);
mDrawerLl = (LinearLayout) findViewById(R.id.ll_drawer);
mToolBar = (Toolbar) findViewById(R.id.toolbar);
}
private void setViews() {
setSupportActionBar(mToolBar);
}
private void setListeners() {
mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mDrawerLayout.isDrawerOpen(mDrawerLl)) {
mDrawerLayout.closeDrawer(mDrawerLl);
}else {
mDrawerLayout.openDrawer(mDrawerLl);
}
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:toolbar="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawerlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:id="@+id/ll_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:background="@color/colorPrimary"
toolbar:navigationIcon="@mipmap/ic_launcher"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize" />
<TextView
android:gravity="center"
tools:text="Hello world"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<LinearLayout
android:id="@+id/ll_drawer"
android:background="@color/colorAccent"
android:layout_gravity="left"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
tools:text="clickBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
效果如下