android - 片段中的 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 ?
解决方案
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)
}
推荐阅读
- javascript - 父补偿。没有在听孩子 $emit
- .net-core - .Net-Core 2.2 MassTransit.ConfigurationException:状态机未正确配置
- sql - 使用循环更新耗时太长
- virtual-machine - 如何将我的虚拟机共享给其他人?
- javascript - 为什么使用 express 将数组发送到前端时 Json stringify 有帮助?
- objective-c - iOS 13 用户的 NSNumberFormatter 忽略 setRoundingIncrement
- python - 如何在小数点后附加4个数字的浮点数?
- java - Intellij Idea 2019.2 更新后在 Intellij 中导入项目时没有下一个和上一个按钮
- php - 未发送来自表单的变量 $message 内容传递
- python - 使用 Python 从 excel 数据构建 XML