Kotlin 一行代码创建Fragment 实例
以后再也不用在Fragment中写newInstance了
/**实例化 Fragment*/
inline fun <reified T : Fragment> Context.newInstanceFragment(): T {
val args = Bundle()
val className = T::class.java.name;
val clazz = FragmentFactory.loadFragmentClass(
classLoader, className)
val f = clazz.getConstructor().newInstance()
if (args != null) {
args.classLoader = f.javaClass.classLoader
f.arguments = args
}
return f as T
}
/**实例化 Fragment*/
inline fun <reified T : Fragment> Context.newInstanceFragment(args: Bundle?): T {
val className = T::class.java.name;
val clazz = FragmentFactory.loadFragmentClass(
classLoader, className)
val f = clazz.getConstructor().newInstance()
if (args != null) {
args.classLoader = f.javaClass.classLoader
f.arguments = args
}
return f as T
}
/**实例化 Fragment*/
inline fun <reified T : Fragment> Context.newInstanceFragment(vararg pair: Pair<String, String>): T {
val args = Bundle()
pair?.let {
for (arg in pair) {
args.putString(arg.first, arg.second)
}
}
val className = T::class.java.name;
val clazz = FragmentFactory.loadFragmentClass(
classLoader, className)
val f = clazz.getConstructor().newInstance()
if (args != null) {
args.classLoader = f.javaClass.classLoader
f.arguments = args
}
return f as T
}
网友评论