-
-
Save rakshakhegde/eea58a24994ac8ce27842febcc1f2ab0 to your computer and use it in GitHub Desktop.
import android.support.v4.app.Fragment | |
import org.jetbrains.anko.bundleOf | |
/** | |
* Pass arguments to a Fragment without the hassle of | |
* creating a static newInstance() method for every Fragment. | |
* | |
* Declared outside any class to have full access in any | |
* part of your package. | |
* | |
* Usage: instanceOf<MyFragment>("foo" to true, "bar" to 0) | |
* | |
* @return Returns an instance of Fragment as the specified generic type with the params applied as arguments | |
*/ | |
inline fun <reified T : Fragment> instanceOf(vararg params: Pair<String, Any>) | |
= T::class.java.newInstance().apply { | |
arguments = bundleOf(*params) | |
} |
how to using it?
i have fragment with companion object like this
companion object {
private const val SEGMENT_NAME = "segment_name"
private const val TEAMID = "teamid"
private const val TITLE = "title"
fun newInstance(segmentName: String?, teamId: String?, titleBar: String?): NextFragment? = NextFragment().apply {
val args = bundleOf(
SEGMENT_NAME to segmentName,
TEAMID to teamId,
TITLE to titleBar
)
val fragment: NextFragment?=null
fragment?.arguments =args
return fragment
}
}
and how read in fragment OnCreateView
in my activity set by me like this:
private fun loadNextFragment(savedInstanceState: Bundle?) {
if (savedInstanceState == null) {
val leagueFragment = instanceOf(
"SEGMENT_NAME" to "eventsnextleague.php",
"TEAMID" to "4329", "TITLE" to "Next League")
supportFragmentManager
.beginTransaction()
.replace(
R.id.main_container,
leagueFragment,
NextFragment::class.java.simpleName
)
.commit()
}
}
thank
definitively a good to have function
But then you call:
T::class.java.newInstance()
So you actually need the
newInstance
, don't you?