因此,问题在于我的汉堡按钮在启动应用程序时不起作用 - 它可以切换,但是抽屉菜单不是打开的。当我通过从侧面滑动打开和关闭抽屉菜单时,它开始工作...因此,每次开始任何新活动时。
这是我的kotlin代码:
open class BaseActivity : AppCompatActivity(), Observer, NavigationView.OnNavigationItemSelectedListener {
private var drawer: DrawerLayout? = null
fun oncreate() {
val toolbar: android.support.v7.widget.Toolbar = this.findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
val actionBar = this.supportActionBar
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true)
actionBar.setHomeButtonEnabled(true)
}
//val actionbar: ActionBar? = supportActionBar
drawer = findViewById(R.id.drawer_layout)
val navigationView: NavigationView = findViewById(R.id.nav_view)
navigationView.setNavigationItemSelectedListener(this)
toggle = ActionBarDrawerToggle(
this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close
)
actionBar?.apply {
setDisplayHomeAsUpEnabled(true)
setHomeAsUpIndicator(R.drawable.ic_menu)
}
drawer!!.addDrawerListener(toggle)
toggle.syncState()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
drawer!!.openDrawer(GravityCompat.START)
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
drawer!!.openDrawer(GravityCompat.START)
true
}
//other items
}
drawer!!.closeDrawer(GravityCompat.START)
return true
}
和XML代码:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="@drawable/background"
tools:openDrawer="start" android:visibility="visible">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:visibility="visible"/>
//这里有更多元素
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/nav_header"
app:itemTextAppearance="@style/txt_expandable"
app:menu="@menu/drawer_menu" android:visibility="gone">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
我尝试了很多事情来解决这个问题,但是似乎没有任何作用...我完全遵循了Kotlin文档中的步骤以及所有内容,但问题仍然存在。
这是错误:
app:menu="@menu/drawer_menu" android:visibility="gone">
删除android:visibility="gone"
。应该是:
app:menu="@menu/drawer_menu">