S
S
sanke462018-10-18 22:11:30
Android
sanke46, 2018-10-18 22:11:30

How to pass class to {Kotlin} method?

I have a method where you need to pass the class to change the fragment "Class" does not accept

fun startFragment(activity: FragmentActivity, clazz: Class<?>): Unit {

        var fragment =  clazz
        var fragmentManager = activity?.supportFragmentManager
        fragmentManager
                ?.beginTransaction()
                ?.replace(R.id.content_frame, fragment.newInstance())
                ?.commit()
    }

gives an error where fragment.newInstance(), How to solve this problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
illuzor, 2018-10-18
@sanke46

Do you really need reflection there?
Try something like this:

inline fun <reified T:Fragment>startFragment(activity: FragmentActivity){

    var fragmentManager = activity?.supportFragmentManager
    fragmentManager
            ?.beginTransaction()
            ?.replace(R.id.content_frame,  T::class.java.newInstance())
            ?.commit()
}

// вызов
startFragment<MyFragment>(activity)

But it would be better to just pass the fragment instance:
fun startFragment(activity: FragmentActivity, fragment:Fragment){
    var fragmentManager = activity?.supportFragmentManager
    fragmentManager
            ?.beginTransaction()
            ?.replace(R.id.content_frame, fragment)
            ?.commit()
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question