Переключатель ящика панели действий отображается на панели приложений, но не работает?

Я создал класс BaseActivity, от которого наследуются все действия, чтобы я мог добавлять макет ящика во все свои действия.

Кнопка Drawer Toggle отображается в AppBar, но когда я нажимаю на нее, ничего не происходит!

Вот код для BaseActivity.kt:

open class BaseActivity : AppCompatActivity() {

private var dl: DrawerLayout? = null
private var t: ActionBarDrawerToggle? = null
private var nv: NavigationView? = null

  override fun onCreate(savedInstanceState: Bundle?) {
   super.onCreate(savedInstanceState)
     setContentView(R.layout.base_activity)
     dl = findViewById(R.id.drawer_layout)
     t = ActionBarDrawerToggle(this, dl,  R.string.drawer_open, R.string.drawer_close)
      supportActionBar?.setDisplayShowTitleEnabled(true);
      supportActionBar?.setHomeButtonEnabled(true);
      supportActionBar?.setDisplayHomeAsUpEnabled(true);
     dl?.addDrawerListener(t!!)
     t?.syncState()

     nv = findViewById(R.id.navigation_view)
    nv?.setNavigationItemSelectedListener(NavigationView.OnNavigationItemSelectedListener { item ->
        when (item.itemId) {
            R.id.nav_note -> Toast.makeText(this@BaseActivity, "My Account", Toast.LENGTH_SHORT).show()
            R.id.nav_calendar -> Toast.makeText(this@BaseActivity, "Settings", Toast.LENGTH_SHORT).show()
            R.id.nav_trash -> Toast.makeText(this@BaseActivity, "Trash", Toast.LENGTH_SHORT).show()
            else -> return@OnNavigationItemSelectedListener true
        }
        true
    })
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return if (t?.onOptionsItemSelected(item) == true) {
        true
    } else super.onOptionsItemSelected(item!!)
}

}

и здесь base_activity.xml:

<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BaseActivity">
<!--include layout="@layout/toolbar"/-->

<com.google.android.material.navigation.NavigationView
    android:id="@+id/navigation_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:menu="@menu/drawer_menu"
    app:headerLayout="@layout/nav_header"/>

</androidx.drawerlayout.widget.DrawerLayout>

Для стиля я оставил его в DarkActionBar. Вот как это выглядит Не обращайте внимания на то, что там написано

Я до сих пор не могу понять, что не так и почему это не работает. Я ценю любые предложения от сообщества. Спасибо.


person Oumaima Abou El Mawahib    schedule 16.01.2021    source источник


Ответы (1)


Итак, я изменил свой код на этот, и он работает. Вот новый код для класса BaseActivty.

open class BaseActivity : AppCompatActivity() {
    //var toolbar: Toolbar? = null
    var drawerLayout: DrawerLayout? = null
    var drawerToggle: ActionBarDrawerToggle? = null
    var navigationView: NavigationView? = null
    var mContext: Context? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mContext = this@BaseActivity
        setContentView(R.layout.base_activity)
    }

    override fun setContentView(layoutResID: Int) {
        val fullView = layoutInflater.inflate(R.layout.base_activity, null) as DrawerLayout
        val activityContainer = fullView.findViewById<View>(R.id.activity_content) as FrameLayout
        layoutInflater.inflate(layoutResID, activityContainer, true)
        super.setContentView(fullView)
    }



    private fun setUpNav() {
        drawerLayout = findViewById<View>(R.id.drawer_layout) as DrawerLayout
        drawerToggle = ActionBarDrawerToggle(
            this@BaseActivity,
            drawerLayout,
            R.string.app_name,
            R.string.app_name
        )
        drawerLayout!!.setDrawerListener(drawerToggle)
        supportActionBar!!.setHomeButtonEnabled(true)
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)
        navigationView = findViewById<View>(R.id.navigation_view) as NavigationView


        // Setting Navigation View Item Selected Listener to handle the item
        // click of the navigation menu
        navigationView!!.setNavigationItemSelectedListener(NavigationView.OnNavigationItemSelectedListener { menuItem -> // Checking if the item is in checked state or not, if not make
            // it in checked state
            if (menuItem.isChecked) menuItem.isChecked = false else menuItem.isChecked = true

            // Closing drawer on item click
            drawerLayout!!.closeDrawers()

            // Check to see which item was being clicked and perform
            // appropriate action
            val intent_calendar = Intent(this, CalendarActivity::class.java)
            val intent_add_note = Intent(this, AddActivity::class.java)
            val intent_note = Intent(this, MainActivity::class.java)
            when (menuItem.itemId) {
                R.id.nav_note -> this.startActivity(intent_note)
                R.id.nav_calendar -> this.startActivity(intent_calendar)
                R.id.nav_trash -> Toast.makeText(this, "Trash", Toast.LENGTH_SHORT).show()
                R.id.nav_add_note -> this.startActivity(intent_add_note)
                else -> return@OnNavigationItemSelectedListener true
            }
            false
        })

        // calling sync state is necessay or else your hamburger icon wont show
        // up
        drawerToggle!!.syncState()
    }

    public override fun onPostCreate(savedInstanceState: Bundle?) {
        super.onPostCreate(savedInstanceState)
        setUpNav()
        drawerToggle!!.syncState()
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        if (newConfig != null) {
            super.onConfigurationChanged(newConfig)
        }
        drawerToggle!!.onConfigurationChanged(newConfig)
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return if (drawerToggle?.onOptionsItemSelected(item) == true) {
            true
        } else super.onOptionsItemSelected(item!!)
    }
}

а вот код для его xml

<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".BaseActivity"
    >
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <FrameLayout
            android:id="@+id/activity_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navigation_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/drawer_menu"
        app:headerLayout="@layout/nav_header"/>

</androidx.drawerlayout.widget.DrawerLayout>

Вот ответ, который мне помог (я не использовал панель инструментов и оставил стиль Theme.AppCompat.Light.DarkActionBar) https://stackoverflow.com/a/42533759/15018682

person Oumaima Abou El Mawahib    schedule 24.01.2021