androidandroid-fragmentsandroid-viewbinding

ViewBinding in Fragment


I want to use ViewBinding to work with Views in Fragment.

FragmentBlankBinding binding;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    binding = FragmentBlankBinding.inflate(inflater, container, false);
    return binding.getRoot();
}

But when I try to get RecyclerView from that binding like this:

binding.notesRecyclerView.setAdapter(adapter);

I get NullPointerException:

java.lang.NullPointerException: Attempt to read from field 'androidx.recyclerview.widget.RecyclerView com.myapps.notes.databinding.FragmentBlankBinding.notesRecyclerView' on a null object reference

P.S. here's 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>

Solution

  • This working fine for me:

    private FragmentJavaPracticeBinding binding;
    
    @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            binding = FragmentJavaPracticeBinding.inflate(inflater,container,false);
            return binding.getRoot();
        }
    
        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            binding.notesRecyclerView.setVisibility(View.VISIBLE);//this hide/show recyclerview visibility 
            Log.d("TAG", "hidden: ");
        }