简体   繁体   中英

How to write PopupMenu in Kotlin in RecycleViwer?

This is first time that i am creating Andorid app so please help, so i have this code in my adapter:

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.view.setOnClickListener {
            d("daniel", "clicked")
        }

        holder.view.img_more.setOnClickListener{
            val popupMenu = PopupMenu(this, it)
            popupMenu.setOnMenuItemClickListener { item ->
                when(item.itemId){
                    R.id.action_settings ->{
                        Toast.makeText(this,"this is toast message",Toast.LENGTH_SHORT).show()
                        true
                    }
                    R.id.action_settings ->{
                        Toast.makeText(this,"this is toast message",Toast.LENGTH_SHORT).show()
                        true
                    }
                    else -> false
                }
            }
            popupMenu.inflate(R.menu.menu_prijem_posiljke)
            popupMenu.show()
        }
    }

In the line:

val popupMenu = PopupMenu(this, it)

for "this" context says required context. What do i need to put there for this to work? thank you

Every View object in Android has an associated context which is the Activity or Fragment class which instantiated the view. You can use the context property of the view to gain a context but you need to be careful not to leak it. If you really need a context, you can pass applicationContext as a dependency to the Adapter class. But as a quick solution you can replace your code with the following as suggested by @Jeel and it should work.

 override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.view.setOnClickListener {
        d("daniel", "clicked")
    }

    holder.view.img_more.setOnClickListener{
        val popupMenu = PopupMenu(holder.view.context, it)
        popupMenu.setOnMenuItemClickListener { item ->
            when(item.itemId){
                R.id.action_settings ->{
                    Toast.makeText(this,"this is toast message",Toast.LENGTH_SHORT).show()
                    true
                }
                R.id.action_settings ->{
                    Toast.makeText(this,"this is toast message",Toast.LENGTH_SHORT).show()
                    true
                }
                else -> false
            }
        }
        popupMenu.inflate(R.menu.menu_prijem_posiljke)
        popupMenu.show()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM