Search code examples
androidkotlinandroid-fragmentsonclicklistener

start an activity from a fragment (app is not starting)


im still new to Kotlin... i have a drawer, which changes between fragments.

in the home fragment i want to have a button, which starts an activity. my fragment class looks like this:

private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

class Home : Fragment() {
    private var param1: String? = null
    private var param2: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {

            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        imageButton1.setOnClickListener {
            /* Start Activity */
            val i = Intent(activity, strooptest::class.java)
            startActivity(i)
        }
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment Home.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            Home().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}

my app won't start and I'm not sure what im doing wrong here. Also im not having any Errors or Exceptions!


Solution

  • If this is all of your code for the HomeFragment then it seems like you are missing a declaration of imageButton1?

    I would recommend reading into how to create a fragment to get a better understanding. Annoyingly the official Android documentation for creating a fragment seems lacking but this article seems to have a nice code example, especially referring to onCreateView and onViewCreated.