jeudi 21 mars 2019

How to use reflection in Kotlin

I have a fragment manager to show/hide fragments in my app. Right now when I want to show a fragment from any activity or fragment I call this method from the manager

 fun show(manager: FragmentManager, fragmentTag: String, container: Int, data: Any?): Companion {
        var fragment = manager.findFragmentByTag(fragmentTag)
        if (fragment != null) {
            manager.popBackStack(fragmentTag, 0)
        } else {
            addFragment(manager, getFragment(fragmentTag, manager, data)!!, container, fragmentTag)
        }
        return this
    }

 private fun getFragment(fragmentTag: String, manager: FragmentManager, data: Any?): Fragment? {
        when (fragmentTag) {
            MenuFragment.TAG -> return getMenuFragment(manager)
            TagsFragment.TAG -> return getTagsFragment(manager)
            ...
        }
        return null
    }

with return a fragment with a specific class

private fun getMenuFragment(manager: FragmentManager): Fragment {
        var fragment = manager.findFragmentByTag(MenuFragment.TAG) as MenuFragment?
        if (fragment == null) {
            fragment = MenuFragment.newInstance()
        }
        return fragment
    }

I would like to have an strategy to avoid create one method every time I need to implement a new fragment, so I was thinking about generics or maybe reflection wich I have never used before.

Is there any way to do this using reflection? or another better strategy?

Thanks for any help.





Aucun commentaire:

Enregistrer un commentaire