【发布时间】:2021-02-07 18:44:55
【问题描述】:
我的布局landing_item.xml
<androidx.appcompat.widget.LinearLayoutCompat
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".landing.MainActivity">
<com.google.android.material.textview.MaterialTextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<com.google.android.material.textview.MaterialTextView
android:id="@+id/description"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</androidx.appcompat.widget.LinearLayoutCompat>
片段
class LandingItemFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = inflater.inflate(R.layout.landing_item, container, false)
}
适配器
class LandingItemPageAdapter(fa: FragmentActivity) : FragmentStateAdapter(fa) {
override fun getItemCount(): Int = 3
override fun createFragment(position: Int): Fragment = LandingItemFragment()
override fun onBindViewHolder(
holder: FragmentViewHolder,
position: Int,
payloads: MutableList<Any>
) {
super.onBindViewHolder(holder, position, payloads)
val binder = LandingItemBinding.bind(holder.itemView)
binder.title.text = "Test"
binder.description.text = "This is a test"
}
}
调用 bind 时会因为找不到元素而崩溃
2021-02-07 10:40:05.183 8904-8904/com.comp.app E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.comp.app, PID: 8904
java.lang.NullPointerException: Missing required view with ID: com.comp.app/description
at com.comp.app.databinding.LandingItemBinding.bind(LandingItemBinding.java:88)
【问题讨论】:
标签: android android-viewbinding