美文网首页
Kotlin 一行代码创建Fragment 实例

Kotlin 一行代码创建Fragment 实例

作者: CHNEGC | 来源:发表于2020-05-26 12:41 被阅读0次

    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
    }

    相关文章

      网友评论

          本文标题:Kotlin 一行代码创建Fragment 实例

          本文链接:https://www.haomeiwen.com/subject/bvbmahtx.html