我觉得我做错了,但是这是我的情况。 我得到一个片段中的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
}
Activity
同时显示两个片段?如果是这样,你可以通过它传递数据。或者实现某个接口/可观察/ livedata打发碎片之间的数据。Fragment A
获取数据,然后更改Fragment A
到Fragment 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 }
事实上,这是可以从一个片段传递对象到另一个给你的对象类实现Parcelable。并通过调用putParcelable捆绑对象上通过捆绑的对象。
1. class CurrancyModel : Parcelable {
//Implement Parcelable
}
并通过它通过捆绑的片段之间。
2.var fragment = YourFragment().apply {
arguments = Bundle().apply{ putParcelable("dataKey",yourData) }
}
一个想法可能是使用一个单独的数据类,与具有HashMap<String, Object>
了某种ID的创建自己的密钥,然后将值是你希望能够检索对象。所以在onResponse
您将您的数据添加到在数据类的HashMap
,然后就从其他类检索。