简体   繁体   English

使用片段的不同方式

[英]Different ways to use Fragments

I am developing an app with Firebase.我正在使用 Firebase 开发一个应用程序。 But whenever I use the onViewCreated method, the button does not respond to any clicks.但是每当我使用onViewCreated方法时,按钮都不会响应任何点击。 But when I use the onCreateView , it works.但是当我使用onCreateView时,它可以工作。

Here is my LoginFragment (Button does not respond to clicks):这是我的 LoginFragment (按钮不响应点击):

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.问题在于,在onViewCreated中,您正在使用FragmentLoginBinding.inflate(layoutInflater)创建绑定 object 但您没有将该绑定连接到视图,因此无论您使用该 object 做什么都不会对视图产生影响。

FragmentLoginBinding.inflate(layoutInflater) creates a new binding object and also inflate a new view to which it is connected. FragmentLoginBinding.inflate(layoutInflater)创建一个新的绑定 object 并膨胀它所连接的新视图。 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.如果你真的想要的话,在onViewCreated里面,这将创建一个与你在片段中拥有的视图的绑定。

Said that, creating the binding already in onCreateView is actually recommended by the Android documentation .也就是说, Android 文档实际上建议在onCreateView中创建绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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