Home > Net >  Difference between onCreateView and onViewCreated in Fragment - Kotlin
Difference between onCreateView and onViewCreated in Fragment - Kotlin

Time:06-27

I know this question has been asked many times but just wanted to have some more clarity.

So i wanted to create a simple fragment with a button that should change the fragment when clicked - very simple and basic one.

hence i create a function, and called it on onCreateView. Nothing happeded.

Then i created onViewCreated after onCreateView and called the same function in it.

It Worked.

My Question is What exactly made it work ?

here is the code

class homeFragment : Fragment() {

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_home, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    hello()
}
 fun hello()
{
    val button = view?.findViewById<Button>(R.id.button_login)
              button?.setOnClickListener{
                  val action = homeFragmentDirections.actionHomeFragmentToLoginFragment()
                  findNavController().navigate(action)

            Toast.makeText(context,"wao",Toast.LENGTH_LONG).show()
        }
    }

}

CodePudding user response:

As per your comments, you did something like this:

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    return inflater.inflate(R.layout.fragment_home, container, false)
    hello() // the method has already returned a View, so this call is never reached.
}

So, when you call hello() in onCreateView after the return statement
the method has no effect because of the return statement.

Since onViewCreated is called after the onCreateView,
the underlying View is no more null in your hello function.

CodePudding user response:

You need to inflate the view before calling the function:

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {        
        val fragmentHome = inflater.inflate(R.layout.fragment_home, container, false)
        hello(fragmentHome)
        return fragmentHome;
    }

Change your hello function:

fun hello(view: View)
{
    ....
  • Related