简体   繁体   中英

NullPointerException when using Kotlin ViewBinding inside Fragment

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

Put view before start_button like below code

 view.start_button.setOnClickListener(
                Navigation.createNavigateOnClickListener(R.id.action_fragmentStart_to_fragmentQuestion,null)
            )

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)
            )
    }

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM