我的布局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)发布于 2021-02-08 05:03:48
您需要将项目布局包装在<layout>标记中
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<androidx.appcompat.widget.LinearLayoutCompat
android:orientation="vertical"
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>
</layout>https://stackoverflow.com/questions/66091759
复制相似问题