1.介绍:DrawerLayout是一个布局,在布局中允许放入两个直接子控件,第一个子控件是主屏幕中显示的内容,
第二个子控件是滑动菜单中显示的内容。
*注意:第二个子控件必须设置layout_gravity属性,left指在左边,right指在右边,start指根据系统语言进行判断。
*ToolBar最左侧的这个按钮叫做HomeAsUp按钮,默认图标为一个箭头,id永为android.R.id.home。
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawer_layout"
android:background="#fff">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
</FrameLayout>
<TextView
android:text="This is menu"
android:textSize="30sp"
android:background="#fff"
android:textColor="#000"
android:layout_gravity="start"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.DrawerLayout>
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout=findViewById(R.id.drawer_layout);
toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar=getSupportActionBar();
if (actionBar!=null){
//显示导航按钮
actionBar.setDisplayHomeAsUpEnabled(true);
//设置导航按钮图标
actionBar.setHomeAsUpIndicator(R.mipmap.ic_launcher);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
mDrawerLayout.openDrawer(Gravity.START);
break;
}
return true;
}
}