Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

解決 DrawerLayout 側滑菜單從右側滑出報錯的問題

編輯:關於 Android 開發

解決 DrawerLayout 側滑菜單從右側滑出報錯的問題


程式碼如下:

 <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorPrimary" android:minHeight="?attr/actionBarSize"/> <android.support.v4.widget.DrawerLayout android:id="@+id/dl_home" android:layout_width="match_parent" android:layout_height="match_parent"> <FrameLayout android:id="@+id/dl_container" android:layout_width="match_parent" android:layout_height="match_parent"/> <LinearLayout android:id="@+id/dl_menu" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="end" android:background="@color/white" android:orientation="vertical"/> </android.support.v4.widget.DrawerLayout>
 mToolbar = (Toolbar) findViewById(R.id.toolbar); dlHome = (DrawerLayout) findViewById(R.id.dl_home); drawerToggle = new ActionBarDrawerToggle(this, dlHome, mToolbar, 0, 0); drawerToggle.syncState();

問題描述:

使用 Toolbar、DrawerLayout 和 ActionBarDrawerToggle 實現側滑菜單效果,按鈕點擊實現左側滑出沒問題,但改成右側滑出
報錯:No drawer view found with gravity LEFT

這個問題的根源在於 ActionBarDrawerToggle 預設處理的是左側(LEFT/START)的抽屜,當我們改用右側滑出時,需要自行處理工具列按鈕的點擊事件。

解決辦法:為 mToolbar 的導航按鈕添加一個點擊監聽,具體實現如下:

 mToolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dlHome.isDrawerOpen(GravityCompat.END)) { dlHome.closeDrawers(); } else { dlHome.openDrawer(Gravity.END); } } }); 

透過手動控制抽屜的開關(使用 Gravity.END 代表右側),就能避免 ActionBarDrawerToggle 因找不到左側 drawer view 而報錯,問題便迎刃而解。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved