首页 > 解决方案 > 片段中的 setBackgroundColor recycleView

问题描述

我试图在片段中设置背景颜色 recycleView,就像在教程中一样。

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {

    recycleViewRandom.setBackgroundColor(Color.BLUE)

    return inflater.inflate(R.layout.fragment_recycle_view, container, false)
}

这是我的xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragments.MainFragment">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycleViewRandom"
        android:layout_width="368dp"
        android:layout_height="495dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />
</android.support.constraint.ConstraintLayout>

一切看起来都不错,与教程中的一样,但我从 IDE 得到:

空对象引用上的 setBackgroundColor(int)'

怎么可能是 null ?

标签: androidkotlin

解决方案


NullPointerException当应用程序尝试使用具有空值的对象引用时抛出。

宣布

 lateinit var                            recycleViewRandom: RecyclerView

然后

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        contentView = inflater.inflate(R.layout.fragment_recycle_view, container, false)
        initUI(contentView)
        return contentView
    }

你应该初始化RecyclerView

    fun initUI(contentView: View)
    {
        recycleViewRandom= contentView.findViewById(R.id.recycleViewRandom)
        recycleViewRandom.setBackgroundColor(Color.BLUE)
     }

推荐阅读