How to get String Resource within ViewPager Adapter?

后端 未结 9 1831
孤城傲影
孤城傲影 2020-12-31 07:42

I trying to set the title for my viewpager, I can\'t seem to get it to work. I tried Resources.getSystem().getString(R.string.title1); and also tried to pass a context. Coul

9条回答
  •  孤城傲影
    2020-12-31 08:32

    With Kotlin I do this by sending context to the adapter, as below:

    class FmAdapter(val context: Context, fm: FragmentManager) : FragmentStatePagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
    
        private val fragments = arrayListOf()
    
        init {
            fragments.add(Fragments(R.string.title1, FragmentOne()))
            fragments.add(Fragments(R.string.title2, FragmentTwo()))
        }
    
        override fun getCount(): Int = fragments.size
    
        override fun getItem(position: Int): Fragment = fragments[position].fragment
    
        override fun getPageTitle(position: Int): CharSequence? = context.getString(fragments[position].title)
    }
    

    with data class:

    data class Fragments(@StringRes val title: Int, val fragment: Fragment)
    

    and simple call from activity, like:

    rv.adapter = FmAdapter(this, supportFragmentManager)
    

提交回复
热议问题