我正在制作一个非常简单的webview应用程序,将网站的不同子页面放在不同的选项卡下(使用tablayout),即消息,订单等。单个的webview是使用fragments创建的。其理念是用户可以快速地在页面之间来回切换。在测试时,当我直接切换到我正在使用的选项卡旁边的选项卡然后再切换回来时,页面和我离开选项卡时完全一样。然而,我切换到一个标签,是一个以上的标签远离我目前在一个,然后切换回上一个标签,页面被重新加载。我希望当用户切换到任何其他选项卡时,页面状态能够被记住。如何做到这一点?
TL;DR:如何保留webview状态切换时使用tablayout的片段,每个显示不同的webview标签?
作为参考,其中一个片段的代码为:class BrowseFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val myView = inflater.inflate(R.layout.fragment_browse, container, false)
val webViewBrowse = myView.findViewById(R.id.webViewBrowse) as WebView;
webViewBrowse.setWebViewClient(WebViewClient())
webViewBrowse.loadUrl("https://websitehome.page")
webViewBrowse.settings.setJavaScriptEnabled(true)
return myView
}
}
由SectionsPagerAdapter.tk控制:
class SectionsPagerAdapter(private val context: Context, fm: FragmentManager) :
FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment {
// getItem is called to instantiate the fragment for the given page.
return when (position) {
0 -> {
BrowseFragment()
}
1 -> {
SecondFragment()
}
2 -> {
ThirdFragment()
}
3 -> {
FourthFragment()
}
else -> BrowseFragment()
}
}
override fun getPageTitle(position: Int): CharSequence? {
return context.resources.getString(TAB_TITLES[position])
}
override fun getCount(): Int {
// Show 4 total pages.
return 4
}
}
寻呼机适配器已弃用
使用ViewPager2
首先将offscreenPageLimit设置为viewPager2
//YOUR_ID
yourViewPager2.offscreenPageLimit =3
使用PagerStateAdapter
class SectionsPagerAdapter(mActivity: FragmentActivity) : FragmentStateAdapter(mActivity) {
private var mBrowseFragment: BrowseFragment? = null
private var mSecondFragment: SecondFragment? = null
private var mThirdFragment: ThirdFragment? = null
private var mFourthFragment: FourthFragment? = null
override fun getItemCount() = 4
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> {
if (mBrowseFragment != null) {
mBrowseFragment!!
} else {
mBrowseFragment = BrowseFragment()
mBrowseFragment!!
}
}
1 -> {
if (mSecondFragment != null) {
mSecondFragment!!
} else {
mSecondFragment = SecondFragment()
mSecondFragment!!
}
}
2 -> {
if (mThirdFragment != null) {
mThirdFragment!!
} else {
mThirdFragment = ThirdFragment()
mThirdFragment!!
}
}
3 -> {
if (mFourthFragment != null) {
mFourthFragment!!
} else {
mFourthFragment = FourthFragment()
mFourthFragment!!
}
}
else -> {
// Else part won't call no need to consider NULL
mBrowseFragment!!
}
}
}
}
FragmentStateAdapter有多个构造函数选项。我在这个示例中使用了activity。
FragmentStateAdapter(@NonNull FragmentActivity fragmentActivity)
FragmentStateAdapter(@NonNull Fragment fragment)
FragmentStateAdapter(@NonNull FragmentManager fragmentManager,
@NonNull Lifecycle lifecycle)