我想使用 ViewBinding 来处理 Fragment 中的视图。
FragmentBlankBinding binding;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binding = FragmentBlankBinding.inflate(inflater, container, false);
return binding.getRoot();
}
但是当我尝试从这样的绑定中获取 RecyclerView 时:
binding.notesRecyclerView.setAdapter(adapter);
我得到 NullPointerException:
java.lang.NullPointerException:尝试从空对象引用上的字段“androidx.recyclerview.widget.RecyclerView com.myapps.notes.databinding.FragmentBlankBinding.notesRecyclerView”读取
PS这里是fragment_blank.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".BlankFragment">
<com.getbase.floatingactionbutton.FloatingActionButton
android:id="@+id/newNoteActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_margin="3dp"
android:elevation="10dp"
app:fab_icon="@drawable/ic_baseline_add_24" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/notesRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
</RelativeLayout>