Kotlin 一行代码创建Fragment 实例

2020-05-26  本文已影响0人  CHNEGC

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
}
上一篇 下一篇

猜你喜欢

热点阅读