I am completely new to android studio (kotlin) and am attempting to open a new activity from a fragment using a button. I apologize if this is simple, i just can not seem to figure it out.
This is what i have so far, it does not do anything when i run the emulator and click on the button
class HomeFragment : Fragment(R.layout.fragment_home) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val btntakepicture: Button? = view?.findViewById<Button>(R.id.btn_take_picture)
btntakepicture?.setOnClickListener {
requireActivity().run {
startActivity(Intent(this, takepicture::class.java))
finish()
}
}
}
}
3
Answers
There is almost no reason to ever override
onCreate
in a fragment. It is called before your view is created so you have no button to set a listener on at that point. You should overrideonViewCreated
instead.To fix this, you can move the code to the onViewCreated method instead, which is called after the view is created:
Override
onViewCreated
method as follow: