通过两个片段之间的数据类

问题描述 投票:2回答:3

我觉得我做错了,但是这是我的情况。 我得到一个片段中的JSON数据,然后用GSON处理它的数据类和显示它。我需要的是另一个片段中的自定义微调适配器这是准备再次使用这些数据。

虽然我知道这是不可能的传递对象,所以我怎么可以这样!?我曾尝试使用捆绑,并没有奏效

该方法onResponse(第一个片段)

            override fun onResponse(call: Call?, response: Response?) {
            val jsonString = response?.body()?.string()
            val gson = GsonBuilder().create()
            val data = gson.fromJson(jsonString,currancyModel::class.java)
            countryData = data
            activity?.runOnUiThread {
                rootView.recyclerView.adapter = CountryAdapter(data)
                }
        }

数据类

data class currancyModel(val items: List<Item>)
data class Item(val countray :String,val rate:String)

在第二个片段中自定义微调适配器getView(我需要我的数据在这里)

    override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
    val view    = inflater.inflate(R.layout.custome_spinner,null)
    val img = view.findViewById<View>(R.id.spinner_image) as ImageView
    val countary_name     = view.findViewById<View>(R.id.spinner_country) as TextView
    img.setImageResource(R.drawable.us)
    countary_name.setText(country!![p0].countray)
    return view
}
android android-fragments kotlin
3个回答
1
投票
  1. 你在你的Activity同时显示两个片段?如果是这样,你可以通过它传递数据。或者实现某个接口/可观察/ livedata打发碎片之间的数据。
  2. 如果Fragment A获取数据,然后更改Fragment AFragment B,让你的数据类Parcelable,然后将其作为参数传递创造Fragment B时:
companion object {
    fun newInstance(yourData : DataClass) = FragmentB().apply { arguments = Bundle().apply {  putParcelable("dataKey",yourData) }
}

注意:您可以@Parcelize注解你的数据类。那么编译器会为你所有Parcelable方法和工厂类。

当你通过数据Fragment B上创作,与检索,例如:

val data: YourData by lazy { arguments?.getParcelable("dataKey") as YourData }


2
投票

事实上,这是可以从一个片段传递对象到另一个给你的对象类实现Parcelable。并通过调用putParcelable捆绑对象上通过捆绑的对象。

1. class CurrancyModel : Parcelable {
  //Implement Parcelable 
}

并通过它通过捆绑的片段之间。

2.var fragment = YourFragment().apply {
   arguments = Bundle().apply{ putParcelable("dataKey",yourData) }
}

0
投票

一个想法可能是使用一个单独的数据类,与具有HashMap<String, Object>了某种ID的创建自己的密钥,然后将值是你希望能够检索对象。所以在onResponse您将您的数据添加到在数据类的HashMap,然后就从其他类检索。

© www.soinside.com 2019 - 2024. All rights reserved.