0

I want to create a bottom sheet template for my project to avoid repetitive codes.

So I created a template layout with an empty linear layout for placing content view:

<!-- fragment_custom_bottom_sheet.xml -->

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">

<!-- my custom header -->

<!-- LinearLayout: place for content view -->
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/rootLayout"
    android:layoutDirection="rtl"
    android:orientation="vertical">

</LinearLayout>

</LinearLayout> 

And the java class:

<!-- CustomBottomSheetDialogFragment.java -->

public class CustomBottomSheetDialogFragment extends BottomSheetDialogFragment {

    private FragmentCustomBottomSheetBinding binding;

    private View contentView;
    private final int layoutResID;

    public CustomBottomSheetDialogFragment(@LayoutRes int layoutResID) {
        this.layoutResID = layoutResID;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentCustomBottomSheetBinding.inflate(inflater, container, false);
        contentView = LayoutInflater.from(getContext()).inflate(layoutResID, null);
        LinearLayout rootLayout = binding.rootLayout;
        rootLayout.addView(contentView);
        return binding.getRoot();
    }

    public FragmentCustomBottomSheetBinding getBinding() {
        return binding;
    }
}

But when I create a new instance of this

final CustomBottomSheetDialogFragment myBottomSheet = new CustomBottomSheetDialogFragment(R.layout.my_bottom_sheet);

Button confirmAction = myBottomSheet.getBinding().rootLayout.findViewById(R.id.confirm_btn);
Button discardAction = myBottomSheet.getBinding().rootLayout.findViewById(R.id.discard_tn);

it produce the following error:

FATAL EXCEPTION: main

java.lang.NullPointerException: Attempt to read from field
'android.widget.LinearLayout ... .databinding.FragmentCustomBottomSheetBinding.rootLayout'
on a null object reference

Why my rootLayout is empty as the error point to it?

0 Answers0