简体   繁体   中英

Different ways to use Fragments

I am developing an app with Firebase. But whenever I use the onViewCreated method, the button does not respond to any clicks. But when I use the onCreateView , it works.

Here is my LoginFragment (Button does not respond to clicks):

class LoginFragment : Fragment(R.layout.fragment_login) {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val binding = FragmentLoginBinding.inflate(layoutInflater)
        binding.buttonGoogleSignin.setOnClickListener {
            toast("THIS IS NOT WORKING")
            Authentication.getInstance().signIn(context!!, getString(R.string.default_web_client_id)) {
                startActivityForResult(mGoogleClient.signInIntent, RC_GOOGLE_SIGN_IN)
            }
        }
    }
}

In this code, my button responds to clicks:

class LoginFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInFlater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) {
        val view = inflater.inflate(R.layout.fragment_login, container, false)
        val binding = FragmentLoginBinding.bind(view)
        binding.buttonGoogleSignin.setOnClickListener {
            toast("THIS IS WORKING")
            Authentication.getInstance().signIn(context!!, getString(R.string.default_web_client_id)) {
                startActivityForResult(mGoogleClient.signInIntent, RC_GOOGLE_SIGN_IN)
            }
        }
        return view
    }
}

Can someone explain to me why the first approach did not work?

The problem is in the fact that in onViewCreated you are creating a binding object with FragmentLoginBinding.inflate(layoutInflater) but you are not connecting that binding to the view, so whatever you do with that object will not have effect on the view.

FragmentLoginBinding.inflate(layoutInflater) creates a new binding object and also inflate a new view to which it is connected. But you are not using that view in your fragment, so using that method is not the correct choice.

So you can do something like:

val binding = FragmentLoginBinding.bind(getView())

inside onViewCreated if you really want, and that will create a binding with the view you have in your fragment.

Said that, creating the binding already in onCreateView is actually recommended by the Android documentation .

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