0
我有一個RecyclerView
與兩個ViewHolder
。一個用於標題,另一個用於實際項目。現在我想要改變標題中的背景顏色(它是一個ImageView
),具體取決於點擊了哪個列表項。我試過,但有:如何在RecyclerView元素中更改標題背景色onClick?
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setBackgroundColor(int)' on a null object reference
這是我的代碼:
case class MyItemHolder(view: View, items: Array[Entry]) extends RecyclerView.ViewHolder(view) with MyHolder with View.OnClickListener{
view.setOnClickListener(this)
lazy val currentItem = items(getAdapterPosition - 1)
val textView: TextView = view.findViewById(R.id.textView).asInstanceOf[TextView]
val imageView: ImageView = view.findViewById(R.id.imageView).asInstanceOf[ImageView]
def bind(e: Entry): Unit = textView.setText(e.name)
override def onClick(view: View): Unit = {
Toast.makeText(getApplicationContext, s"You clicked ${currentItem.name}!", Toast.LENGTH_SHORT).show()
imageView.setBackgroundColor(Color.parseColor(currentItem.color)) // crashed with NPE
}
}
的頭的ImageView
實際上是在自己ViewHolder
:
case class MyHeaderHolder(view: View) extends RecyclerView.ViewHolder(view) with MyHolder {
val imageView: ImageView = view.findViewById(R.id.imageView).asInstanceOf[ImageView]
val image = ContextCompat.getDrawable(getApplicationContext, R.drawable.title)
def bind(): Unit = imageView.setImageDrawable(image)
}
如何從訪問我的MyItemHolder
?
謝謝,但它仍然拋出NPE。 – user3350744