在RecyclerView Adapter中使用带有Activity作为参数的方法

时间:2018-05-31 17:46:45

标签: android layout android-recyclerview kotlin adapter

我的RecyclerView适配器存在问题。 我想在我的RecyclerView Adapter类中调用此方法:

class UIManager {
   companion object {
      fun updateElem(fromActivity: Activity?)
      {
        if (fromActivity == null) { return }

        val number: TextView = fromActivity.findViewById(R.id.box)

        var chest = fromActivity.resources.getString(R.string.chests)
        if (DataManager.boxes?.size!! < 2)
            chest = fromActivity.resources.getString(R.string.chest)

        number.text = DataManager.boxes?.size?.let { "" + DataManager.boxes?.size + " " + chest } ?: "0 " + chest 
    }
   }
  }

通常我可以在我的Adapter中创建一个方法并将Activity作为参数传递,然后调用updateElem()。

但是我尝试了很多东西并且它对我不起作用,因为即使我这样做,我也会在我的适配器的覆盖方法中调用它,请参阅:

class RecyclerAdapter(val list: ArrayList<String>) : RecyclerView.Adapter<RecyclerAdapter.ViewHolder>()
{

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view: View = LayoutInflater.from(parent.context).inflate((R.layout.box_elem), parent, false)
        return ViewHolder(view)
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getItemViewType(position: Int): Int {
        return position
    }

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        holder.image.setImageResource(R.drawable.original_box)
        holder.itemView.setOnClickListener(View.OnClickListener {
            removeElemAt(position)
        })
    }

    fun removeElemAt(position: Int) {
        list.removeAt(position)
        notifyItemRemoved(position)
        notifyItemRangeChanged(position, list.size)

        // I WANT TO USE THE METHOD HERE
        // !!
        UIManager.updateElem()   <--------------
        //
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
        var image: ImageView = itemView.findViewById(R.id.box_elem)
    }
  }
}

1 个答案:

答案 0 :(得分:1)

如果您需要一个活动参考,您可以在创建时始终将其传递给适配器的构造函数:

class RecyclerAdapter(val activity: Activity, val list: ArrayList<String>)
//...

然后您可以将活动属性用于UIManager.updateElem(activity)调用。