Can anyone help? Starting new activity using onOptionsItemSelected with Kotlin

47 Views Asked by At

After looking through docs and threads I can't find a solution for my case an am wondering if I could get some help / slight nudge with this. I'm not fully understanding this function and am teaching myself as I go.

Here is where I am at: I have an action bar, on the action bar is a hamburger icon, click the hamburger the slideout menu appears. You are presented with various menu items that are available to be selected and take you to a new activity. (example: home, settings, login, etc.) Slideout menu closes upon selection of any of the menu items or the back arrow on the action bar.

Problem: I cannot figure out how to make the menu items selectable with the back arrow included. The toast works on the hamburger icon but not the home menu item. Much appreciated to anyone that can help!

Solution: TBD

HomeActivity.kt:

class HomeActivity : AppCompatActivity() {
    private lateinit var drawerLayout: DrawerLayout
    private lateinit var actionBarDrawerToggle: ActionBarDrawerToggle

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home)

        drawerLayout = findViewById(R.id.my_drawer_layout)
        actionBarDrawerToggle =
            ActionBarDrawerToggle(this, drawerLayout, R.string.nav_open, R.string.nav_close)
        drawerLayout.addDrawerListener(actionBarDrawerToggle)
        actionBarDrawerToggle.syncState()
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
            Toast.makeText(applicationContext, "Clicked Hamburger", Toast.LENGTH_SHORT).show()
            return true
        }
        when (item.itemId) {
            R.id.nav_home -> {
                Toast.makeText(applicationContext, "Clicked Home", Toast.LENGTH_SHORT).show()
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }
    fun launchActivity1(view: View) {}
}
1

There are 1 best solutions below

0
Rob On

seems like your if (actionBarDrawerToggle.onOptionsItemSelected(item)) {} condition is always true and the code below is not reachable - try to comment this part

        if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
            Toast.makeText(applicationContext, "Clicked Hamburger", Toast.LENGTH_SHORT).show()
            return true
        }

and see whats being happened