我正在构建一个应用程序ViewPager2,该应用程序在滑动时显示不同的片段。我的适配器FragmentStateAdapter按此处所述进行扩展。
当我将我的应用程序置于后台然后再次恢复时,当前片段消失了。我需要做什么来确保当前片段正确恢复?
(注意:我问的是FragmentStateAdapter,不是FragmentPagerAdapter或FragmentStatePagerAdapter。)
更新 1:
我的片段类如下:
class PagerFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val layoutResId: Int = arguments!!.getInt(ARG_LAYOUT_RES_ID)
return inflater.inflate(layoutResId, container, false)
}
companion object {
private const val ARG_LAYOUT_RES_ID = "layoutResId"
fun newInstance(layoutResId: Int): PagerFragment {
val args = Bundle()
args.putInt(ARG_LAYOUT_RES_ID, layoutResId)
val fragment = PagerFragment()
fragment.arguments = args
return fragment
}
}
Run Code Online (Sandbox Code Playgroud)
}
我在创建每个片段时传入所需的布局资源 ID。
我的视图寻呼机适配器类如下:
class …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 Moshi 的 Kotlin 代码生成器来获得 Kotlin 中的注释支持。尽管仔细遵循了moshi codegen 文档中的说明,但无法识别中的注释JsonClass,@JsonClass(generateAdapter = true)并且出现以下错误:
error: incompatible types: NonExistentClass cannot be converted to Annotation@error.NonExistentClass()
我的应用程序build.gradle文件如下:
...
apply plugin: 'kotlin-kapt'
android {
...
}
dependencies {
...
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-moshi:2.5.0'
kapt 'com.squareup.moshi:moshi-kotlin-codegen:1.8.0'
}
Run Code Online (Sandbox Code Playgroud)
在@JsonClass当我添加注释认可
implementation("com.squareup.moshi:moshi-kotlin:1.8.0").
但是,moshi反射文档表明只有在使用反射而不是时才需要此依赖项。
知道我错过了什么吗?谢谢!