[英]Why is the savedInstanceState Bundle I pass to my Android Fragment empty on arrival?
在我正在開發的 Android 應用程序中,我有一個列表片段,顯示列表項的RecyclerView
。 我們第一次打開片段時,它從 url 檢索列表,但它不會頻繁更改以繼續重新加載它,所以我想保留數據。 據我所知,Android 方法是使用片段的savedInstanceState
,如下所示:
class ItemListFragment() {
private var itemCards: RecyclerView? = null;
public val Items: ArrayList<Item> = ArrayList<Item>()
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
if ( Items.size == 0 && savedInstanceState != null && savedInstanceState.containsKey("items")) {
val arrayType = object: TypeToken<Array<Item>>() {}.type
val tempItems: Array<Item> = Gson().fromJson(savedInstanceState.getString("items"), arrayType)
Items.addAll(tempItems)
}
}
}
然后我像這樣管理MainActivity
中的狀態:
class MainActivity : AppCompatActivity() {
private lateinit var restoreBundle: HashMap<String, Bundle>
private var currentFragment = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
restoreBundle = HashMap<String, Bundle>()
setContentView(R.layout.activity_main)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
drawFragment(item.itemId)
}
private fun drawFragment(position:Int) {
val fragMan: FragmentManager = getSupportFragmentManager()
val fragmentName = getFragmentName(position)
val bundle:Bundle = restoreBundle.get(fragmentName) ?: Bundle()
var fragment: Fragment? = fragMan.getFragment(bundle, fragmentName)
if ( fragment == null ) {
fragment = ItemListFragment() as Fragment
}
val current = fragMan.findFragmentByTag(currentFragment)
if (current != null) {
val frag = getFragmentName(current.id)
val recover : Bundle = restoreBundle.get(frag) ?: Bundle()
current.onSaveInstanceState(recover)
restoreBundle.set(frag, recover);
}
if (fragmentSet) {
fragMan.beginTransaction()
.replace(R.id.main_content_fragment, fragment!!, fragmentName).commit()
} else {
fragMan.beginTransaction()
.add(R.id.main_content_fragment, fragment!!, fragmentName).commit()
}
currentFragment = fragmentName
}
}
這兩個示例都已精簡到我認為的相關部分,但代碼可能不是我想要做的問題。 基本上,當我切換片段幾次並調用fragMan.getFragment(bundle, fragmentName)
時, bundle
包含正確的保存實例 state 但是當我進入ItemListFragment.onViewStateRestored
(這是我可以放置斷點的下一個地方我可以告訴) savedInstanceState
包是 null。
為什么我傳入的包與正在檢索的包不同,或者將實例 state 傳遞給我的片段的正確方法是什么?
我找不到令人滿意的答案,所以我調整了我的架構,以便從它們自己的服務加載模型並存儲在它們自己的服務中,並在我的MainActivity
中作為伴侶 object 的一部分進行訪問,而不是嘗試使用 Fragment 架構將數據傳遞到片段中。 無論文檔建議如何,尚不清楚后者是否可行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.