[英]How to change header background color onClick in a RecyclerView element?
I have a RecyclerView
with two ViewHolder
. 我有一个带有两个
ViewHolder
的RecyclerView
。 One for a header and one for the actual item. 一个用于标题,一个用于实际项目。 Now I want to change the background color in the header (it's an
ImageView
) depending on what list item was clicked. 现在,我想根据单击的列表项来更改标题(这是
ImageView
)中的背景颜色。 I tried this but got: 我尝试了这个但是得到了:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setBackgroundColor(int)' on a null object reference
This is my code: 这是我的代码:
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
}
}
The ImageView
of the header is actually in its own ViewHolder
: 标头的
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)
}
How can I access it from my MyItemHolder
? 如何从
MyItemHolder
访问它?
Try to access the imageview from within the listener : 尝试从侦听器内部访问imageview:
override def onClick(view: View): Unit = {
Toast.makeText(getApplicationContext, s"You clicked ${currentItem.name}!", Toast.LENGTH_SHORT).show()
val imageView: ImageView = view.findViewById(R.id.imageView).asInstanceOf[ImageView]
imageView.setBackgroundColor(Color.parseColor(currentItem.color)) // crashed with NPE
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.