How to set a long click listener on a MenuItem (on a NavigationView)?

前端 未结 6 1574
无人及你
无人及你 2020-12-11 01:49

How can I set a long click listener on a MenuItem?

I tried this answer, but the method doesn\'t exist for me. Any solutions?

Code:

<         


        
6条回答
  •  南笙
    南笙 (楼主)
    2020-12-11 02:03

    Solution

    This isn't perfect at all, but still better than everyone is suggesting here, because it works on whole item layout, not only on actionview's part.

    Notice:

    1. I tested it only in MaterialComponents library 1.1.0-alpha08, so I don't guarantee that it will work in the future
    2. I already asked devs to provide better API for this, but I don't know if they gonna make it or not
    3. index is the position of an item, BUT it also contains position of: HeaderLayout, Divider, Category (Sub menu header)

    Well, here is the code:

    val navigationView = findViewById(R.id.navigation_view)
    val navigationRecycler = navigationView[0] as RecyclerView // core-ktx extension for ViewGroup
    val navigationLayoutManager = navigationRecycler.layoutManager as LinearLayoutManager
    val navigationAdapter = navigationRecycler.adapter
    
    if (navigationAdapter != null) {
        navigationRecycler.post { // this line is important
            for (index in 0 until navigationAdapter.itemCount) {
                val item = navigationLayoutManager.findViewByPosition(index)
                item?.setOnLongClickListener {
                    Toast.makeText(this, "finally!", Toast.LENGTH_SHORT).show()
                    true
                }
            }
        }
    }
    

提交回复
热议问题