Android實(shí)現(xiàn)側(cè)滑菜單DrawerLayout
本文實(shí)例為大家分享了Android實(shí)現(xiàn)側(cè)滑菜單的具體代碼,供大家參考,具體內(nèi)容如下
點(diǎn)擊左側(cè)滑動(dòng)
效果如下
代碼實(shí)現(xiàn)過(guò)程:
1.導(dǎo)入框架build.gradle中
//materialDesignimplementation ’com.google.android.material:material:1.0.0’
2.xml文件
主要的界面放在DrawerLayout 中,需要強(qiáng)調(diào)的是側(cè)滑菜單也就是下圖顯示的TextView一定要設(shè)置layout_gravity屬性,我是從左側(cè)滑動(dòng)的,所以設(shè)置為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: 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: 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 中將點(diǎn)擊之后觸發(fā)側(cè)邊滑動(dòng)的圖片ic_menu動(dòng)態(tài)放到toolbr中
@Override protected void setupViews() { setupToobar(); drawerLayout = findViewById(R.id.drawer); if (null != getSupportActionBar()) { getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu); } }
android.R.id.home 觸發(fā)左側(cè)滑動(dòng)
@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; }
到這就結(jié)束了。
4.后話
可以在主內(nèi)容區(qū)里面再放一個(gè)布局,里面放各個(gè)fragment,就可以實(shí)現(xiàn)每個(gè)頁(yè)面都有側(cè)滑菜單的效果。側(cè)滑菜單里面的布局可以新建一個(gè)xml文件,然后include,可以看起來(lái)舒服點(diǎn)吧。其他的效果后面慢慢來(lái)吧。github下載地址
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Gitlab CI-CD自動(dòng)化部署SpringBoot項(xiàng)目的方法步驟2. JS sort方法基于數(shù)組對(duì)象屬性值排序3. ASP中解決“對(duì)象關(guān)閉時(shí),不允許操作?!钡脑幃悊栴}……4. JAVA上加密算法的實(shí)現(xiàn)用例5. Django-migrate報(bào)錯(cuò)問題解決方案6. ajax請(qǐng)求添加自定義header參數(shù)代碼7. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)8. 使用Python和百度語(yǔ)音識(shí)別生成視頻字幕的實(shí)現(xiàn)9. 淺談SpringMVC jsp前臺(tái)獲取參數(shù)的方式 EL表達(dá)式10. 基于javascript處理二進(jìn)制圖片流過(guò)程詳解
