这篇文章主要为大家展示了Android如何实现侧滑菜单DrawerLayout,内容简而易懂,希望大家可以学习一下,学习完之后肯定会有收获的,下面让小编带大家一起来看看吧。
代码实现过程:
1.导入框架build.gradle中
//materialDesign
implementation 'com.google.android.material:material:1.0.0'
2.xml文件
主要的界面放在DrawerLayout 中,需要强调的是侧滑菜单也就是下图显示的TextView一定要设置layout_gravity属性,我是从左侧滑动的,所以设置为start
<androidx.drawerlayout.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"
android:id="@+id/drawer"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
app:layout_constraintTop_toTopOf="parent"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</androidx.constraintlayout.widget.ConstraintLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#FFFFFF"
android:fitsSystemWindows="true"
android:text="i am a textView" />
</androidx.drawerlayout.widget.DrawerLayout>
3.MainActivity
绑定xml文件中的toobar
protected void setupToobar() {
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (null != getSupportActionBar()) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
MainActivity 中将点击之后触发侧边滑动的图片ic_menu动态放到toolbr中
@Override
protected void setupViews() {
setupToobar();
drawerLayout = findViewById(R.id.drawer);
if (null != getSupportActionBar()) {
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu);
}
}
android.R.id.home 触发左侧滑动
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
break;
case R.id.item_search:
Toast.makeText(MainActivity.this, "搜索", Toast.LENGTH_SHORT).show();
}
return true;
}
到这就结束了。
4.后话
可以在主内容区里面再放一个布局,里面放各个fragment,就可以实现每个页面都有侧滑菜单的效果。
侧滑菜单里面的布局可以新建一个xml文件,然后include,可以看起来舒服点吧。
其他的效果后面慢慢来吧
以上就是关于Android如何实现侧滑菜单DrawerLayout的内容,如果你们有学习到知识或者技能,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。