android-studiokotlinandroid-fragmentsandroid-activityimagebutton

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).

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)
            }
        }
    }