Issue
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()
}
}
}
Solution
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.
If you still want to use onCreateView
, you can do something like this:
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val fragmentView = inflater.inflate(R.layout.fragment_home, container, false)
hello(fragmentView)
return fragmentView
}
fun hello(buttonHolderView: View?) {
val button = buttonHolderView?.findViewById<Button>(R.id.button_login)
button?.setOnClickListener {
val action = homeFragmentDirections.actionHomeFragmentToLoginFragment()
findNavController().navigate(action)
Toast.makeText(context, "wao", Toast.LENGTH_LONG).show()
}
}
Answered By - DarShan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.