Kotlin 一行代码创建Fragment 实例

Kotlin 一行代码创建Fragment 实例

以后再也不用在Fragment中写newInstance了


/**实例化 Fragment*/
inline fun  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  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  Context.newInstanceFragment(vararg pair: Pair): 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
}

你可能感兴趣的:(Kotlin 一行代码创建Fragment 实例)