当我尝试从Recycler View Adapter启动startActivity()时,Studio显示错误

时间:2018-08-02 19:05:05

标签: android-studio android-activity android-recyclerview kotlin

构建我的第一个应用程序并遇到错误,我不知道。我有一个显示卡片列表的回收站视图。我想单击该卡并打开另一个活动。

这是我的代码:

import android.content.Context
import android.content.Intent
import android.support.v4.content.ContextCompat.startActivity
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import kotlinx.android.synthetic.main.list_tank_item.view.*

class TankAdapter(val context: Context, val tanks: List<Tank>) : RecyclerView.Adapter<TankAdapter.ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, p1: Int): ViewHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.list_tank_item, parent, false)
        return ViewHolder(view)
    }

    override fun getItemCount(): Int {
        return tanks.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val tank = tanks[position]
        holder.setData(tank, position)
    }

    inner class ViewHolder(itemview: View) : RecyclerView.ViewHolder(itemview) {
        var currentTank: Tank? = null
        var currentPosition: Int = 0

        init {
            itemView.setOnClickListener{
                val intent = Intent(context, TankOverviewActivity::class.java)
                var tank_id = currentTank._id.toString()
                intent.putExtra("tank_id", tank_id)
                startActivity(intent)
            }

            itemView.imgEdit.setOnClickListener{
                Toast.makeText(context, currentTank!!.tank_name + " Edit button clicked!", Toast.LENGTH_LONG).show()
            }
        }
        fun setData(tank: Tank?, position: Int) {
            itemView.txvTankName.text = tank!!.tank_name
            itemView.txvTankCapacity.text = tank!!.tank_capacity
            itemView.txvTankType.text = tank!!.tank_type

            this.currentTank = tank
            this.currentPosition = position
        }
    }
}

这是android studio的屏幕: Android Studio problem

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

请尝试

import ...

//use your context as member of your class put private as modifier
class TankAdapter(private val context: Context, val tanks: List<Tank>) : RecyclerView.Adapter<TankAdapter.ViewHolder>() {

    ...

    inner class ViewHolder(itemview: View) : RecyclerView.ViewHolder(itemview) {

        ...

        init {
            itemView.setOnClickListener {

                ...

                //call startActivity from context
                context.startActivity(intent)
            }

            ...

        }

        ...

    }
}