不能使用提供的参数调用以下函数?

时间:2021-02-02 02:59:12

标签: android kotlin

viewHolder.itemView.task_contrtaintLayout_task.setOnClickListener {
                Log.d(TAG,"Clicked $taskId Body")
                val intent = Intent(this, EditTaskActivity::class.java)
                startActivity(intent)
            }

我正在尝试在 ViewHolder 中创建一个意图,为什么会出现这个错误?当我尝试敬酒时会发生同样的事情,在这种情况下我如何定义上下文?

None of the following functions can be called with the arguments supplied:  public constructor Intent(p0: Context!, p1: Class<*>!) defined in android.content.Intent public constructor Intent(p0: String!, p1: Uri!) defined in android.content.Intent

2 个答案:

答案 0 :(得分:0)

您似乎正在尝试从项目持有者的 RecyclerView 适配器开始一项新活动。对于正常的意图工作,您有两种方法:

  1. 将上下文传递给适配器的构造函数并在意图中使用它:

    val intent = Intent(context, SomeActivity::class.java)
    context.startActivity(intent)
    
  2. 使用接口类从适配器点击监听器调用片段/活动方法。

有关意图的更多信息,您可以read documentation

答案 1 :(得分:0)

将上下文作为 Adapter 类的参数。然后访问 ViewHolder 类中的上下文。

class CartImagesAdapter(val items : List<String>, val context: Context) : 
RecyclerView.Adapter<ViewHolder>() {

 // Gets the number of animals in the list
   override fun getItemCount(): Int {
  return items.size
 }
 // Inflates the item views
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder 
{
  return 
 ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_payment_method, 
  parent, false))
   }

// Binds each animal in the ArrayList to a view
override fun onBindViewHolder(holder: ViewHolder, position: Int) {


 }}
 class ViewHolder (view: View) : RecyclerView.ViewHolder(view) {
 // Holds the TextView that will add each animal to
  view.itemView.task_contrtaintLayout_task.setOnClickListener {
            Log.d(TAG,"Clicked $taskId Body")
            val intent = Intent(context, EditTaskActivity::class.java)
            startActivity(intent)
        }   }