我试图像在教程中那样在片段中设置setBackgroundColor 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)&#39;在空对象引用上
怎么可能是null?
答案 0 :(得分:0)
当应用程序尝试使用时,会抛出
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)
}