在我的应用程序中,我有一个带有webview的片段。比方说片段A。当我进入片段B并回到片段A时,webview消失了。我试过webview restoreState(),但它不起作用。它只是显示空的空间。
private var webViewBundle: Bundle? = null
override fun onPause() {
super.onPause()
webViewBundle = Bundle()
webView.saveState(webViewBundle)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupWebView()
}
private fun setupWebView() {
// webview client
if(webViewBundle != null) {
webView.restoreState(webViewBundle)
} else {
searchView.setQuery(viewModel.url.value, true)
webView.loadUrl(searchView.query.toString())
}
}
// change fragment
replaceFragment(
FragmentBNewInstance(),
DashboardActivity.FRAGMENT_RESOURCE_ID,
true,
DashboardActivity.FRAGMENT_BACKSTACK
)
// method to replace fragment
fun replaceFragment(fragment: Fragment?, resId: Int, addToBackstack: Boolean, tag: String) {
try {
if (fragment != null) {
val ft = supportFragmentManager.beginTransaction()
ft.replace(resId, fragment)
if (addToBackstack) {
ft.addToBackStack(tag)
}
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE)
ft.commit()
}
} catch (e: Exception) {
}
}
与其替换片段,不如使用add函数添加片段。
if (fragment != null) {
val ft = supportFragmentManager.beginTransaction()
ft.add(resId, fragment)
if (addToBackstack) {
ft.addToBackStack(tag)
}
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE)
ft.commit()
}