本文实例为大家分享了Android实现侧滑菜单的具体代码,供大家参考,具体内容如下
点击左侧滑动
效果如下
代码实现过程:
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,可以看起来舒服点吧。
其他的效果后面慢慢来吧。
github下载地址
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。