5

I'm trying to add a click listener to a button inside my fragment using kotlin view binding. I am setting the click listener in the onCreateView method. When I do this I get a null pointer exception since the button is not created yet. I thought the kotlin view binding takes care of the view initialization so the button should not be null?

Here is my code:

class FragmentStart : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_start, container, false)
        start_button.setOnClickListener(
            Navigation.createNavigateOnClickListener(R.id.action_fragmentStart_to_fragmentQuestion,null)
        )
        return view
    }
}

Here is the exception:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
dwvldg
  • 293
  • 4
  • 12

2 Answers2

0

Because the view has not been created yet. You should call the view in the onViewCreated () function. read more

 override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

start_button.setOnClickListener(
                Navigation.createNavigateOnClickListener(R.id.action_fragmentStart_to_fragmentQuestion,null)
            )
    }
ThuanPx
  • 22
  • 2
0

kotlinx synthetic under the hood resolves start_button like that:

getView()?.findViewById(R.id.start_button)

getView() returns the fragment's root view if that has been set. This only happens after onCreateView().

That's why views resolved by kotlinx synthetics can only be used in onViewCreated().

Peter F
  • 3,633
  • 3
  • 33
  • 45