Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

kotlin opening new Activity inside of a Fragment

Im getting an error on the second to last close brace.

Error: A ‘return’ expression required in a function with a block body (‘{…}’)

Im trying to open a Activity (TMs) from a ImageButton in my fragement (Dashboard).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Dashboard : Fragment() {


override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View {

    // Inflate the layout for this fragment
    val view = inflater.inflate(R.layout.fragment_dashboard, container, false)

    view.findViewById<ImageButton>(R.id.card1).setOnClickListener {
        val card1 = Intent(activity, TMs::class.java)
        activity?.startActivity(card1)
    }
}

}

>Solution :

The function onCreateView does returns a View. You have inflated the View object, just return it.

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View { 
val view = inflater.inflate(R.layout.fragment_dashboard, container, false)

..code..

return view

Anyways, I do strongly recommend you to init the clickListeners and any other UI logic in onViewCreated().
So we proceed to create the fragment by steps, first we "inflate the view" which is on onCreateView(): View and then once it is created we can add UI logic (as listeners).

It would look like this:

class Dashboard : Fragment() {

    private lateinit var _view: View

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _view = inflater.inflate(R.layout.fragment_dashboard, container, false)

        return _view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        view.findViewById<ImageButton>(R.id.card1).setOnClickListener {
            val card1 = Intent(activity, TMs::class.java)
            activity?.startActivity(card1)
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading