如何在RecyclerView元素中更改标题背景颜色onClick?

时间:2017-02-21 14:11:23

标签: java android scala android-recyclerview

我有两个RecyclerView的{​​{1}}。一个用于标题,一个用于实际项目。现在我想根据点击的列表项更改标题中的背景颜色(它是ViewHolder)。我试过这个,但得到了:

ImageView

这是我的代码:

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) }

访问它?

1 个答案:

答案 0 :(得分:0)

尝试从侦听器中访问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
    }