How to create custom Popup Menu using Kotlin in AndroidStudio?

前端 未结 2 2185
Happy的楠姐
Happy的楠姐 2021-02-19 22:29

I am trying to create popup menu similarly like this on click on a button view in Android using Koltin. I searched for SOF and Google didn\'t find any suggestions. Can anyone pr

2条回答
  •  心在旅途
    2021-02-19 23:23

    Finally, I did it, It may help someone

    Step 1. First, create an activity_main.xml contains a button named my_button

    Step 2. Then take header_menu.xml under res/menu:

    
    
    
        
        
        
    
    
    

    Step 3. Finally, in MainActivity.kt use it like:

    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            my_button.setOnClickListener {
                 showPopup(my_button)
              }
        }
    
        private fun showPopup(view: View) {
            val popup = PopupMenu(this, view)
            popup.inflate(R.menu.header_menu)
    
            popup.setOnMenuItemClickListener(PopupMenu.OnMenuItemClickListener { item: MenuItem? ->
    
                when (item!!.itemId) {
                    R.id.header1 -> {
                        Toast.makeText(this@MainActivity, item.title, Toast.LENGTH_SHORT).show()
                    }
                    R.id.header2 -> {
                        Toast.makeText(this@MainActivity, item.title, Toast.LENGTH_SHORT).show()
                    }
                    R.id.header3 -> {
                        Toast.makeText(this@MainActivity, item.title, Toast.LENGTH_SHORT).show()
                    }
                }
    
                true
            })
    
            popup.show()
        }
    

提交回复
热议问题