skip to Main Content

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


  1. 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 override onViewCreated instead.

    Login or Signup to reply.
  2. To fix this, you can move the code to the onViewCreated method instead, which is called after the view is created:

    Login or Signup to reply.
  3. Override onViewCreated method as follow:

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        val btntakepicture: Button = view.findViewById<Button>(R.id.btn_take_picture)
        btntakepicture.setOnClickListener {
            requireActivity().run {
                startActivity(Intent(this, takepicture::class.java))
                finish()
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search