简体   繁体   English

如何在 RecycleViwer 的 Kotlin 中编写 PopupMenu?

[英]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:这是我第一次创建 Andorid 应用程序,所以请帮忙,所以我的适配器中有以下代码:

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.对于“this”上下文表示所需的上下文。 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. Android 中的每个 View 对象都有一个关联的上下文,即实例化视图的 Activity 或 Fragment 类。 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.如果确实需要上下文,则可以将applicationContext作为依赖项传递给Adapter类。 But as a quick solution you can replace your code with the following as suggested by @Jeel and it should work.但是作为一个快速的解决方案,您可以按照@Jeel 的建议使用以下内容替换您的代码,它应该可以工作。

 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()
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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