【问题标题】:Passing Parceleable Object to Fragment Type Mismatch将 Parcelable 对象传递给片段类型不匹配
【发布时间】:2018-05-03 09:54:11
【问题描述】:

我是 kotlin 的新手,我试图将一个对象从我的适配器传递给一个片段。但是我在booklist 的伴随对象中发现类型不匹配。它说Required: Parceleable Found: List<ResourcesList>?

我也尝试过使用putParcelableArrayListputParcelableArraySerializable,但也有相同的类型不匹配。

我的数据模型如下所示:

@Parcelize
class ResourcesList (val id: Int,
                     val name: String,
                     val content: Contents,
                     val tags: List<Tags>) : Parcelable

@Parcelize
class Contents       (val id: Int,
                     val producers: List<Producers>,
                     val categories: List<Categories>,
                     val isAvailable: Boolean): Parcelable
@Parcelize
class Producers     (val name: String,
                     val role: String): Parcelable
@Parcelize
class Categories    (val id: Int,
                     val name: String): Parcelable

片段

class SeeAllFragment: Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.see_all_layout, container, false)


        val bookslist = arguments.getParceleable("bookslist")

        return view
    }

    companion object {

        fun newInstance(bookslist: List<ResourcesList>?): SeeAllFragment {

            val args = Bundle()
            args.putParcelable("bookslist", bookslist)
            val fragment = SeeAllFragment()
            fragment.arguments = args
            return fragment
        }
    }
}

【问题讨论】:

    标签: android android-fragments kotlin parcelable


    【解决方案1】:

    用于将列表放入捆绑包中:

    args.putParcelableArrayList("bookslist", bookslist as ArrayList<out Parcelable>?)
    

    获取列表:

    val bookslist = arguments.getParcelableArrayList<ResourcesList>("bookslist")
    

    【讨论】:

      【解决方案2】:

      在我的编码中,我使用 Gson。

      companion object {
          const val BOOK_LIST = "bookslist"
          fun getFragment(bookslist: List<ResourcesList>): SeeAllFragment {
              return SeeAllFragment().apply { arguments = Bundle().apply {
                  putString(BOOK_LIST, Gson().toJson(bookslist))
              } }
          }
      }
      

      然后像这样获取数据。

      val bookslist = Gson().fromJson(arguments?.getString(BOOK_LIST), object : TypeToken<List<ResourcesList>>() {}.type)
      

      【讨论】:

      • 为我工作。不要忘记将 gson 库添加到您的应用程序 gradle 文件中。
      猜你喜欢
      • 2014-03-07
      • 1970-01-01
      • 2012-06-05
      • 1970-01-01
      • 1970-01-01
      • 2017-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多