更改选项卡后,ViewPager上的片段不起作用

时间:2018-12-16 14:48:26

标签: android android-viewpager fragment

首先,我创建了2个片段,并且工作正常,但是当我在第一次创建其片段时添加了片段(总共3个片段),但是在刷卡swipeRefresh或更改了tab / pager之后,第一个片段和第三个片段不起作用(但是视图已显示),但是第二个片段运行良好。 这是我的片段适配器

class FragmentAdapter(fragmentManager: FragmentManager) : FragmentPagerAdapter(fragmentManager) {

val mFragmentList: ArrayList<Fragment> = ArrayList()
private val mFragmentTitleList: MutableList<String> = mutableListOf()


override fun getItem(position: Int): Fragment {
    return mFragmentList[position]
}

override fun getCount(): Int {
    return mFragmentList.count()
}

fun addFragment(fragment: Fragment, title: String = "") {
    mFragmentList.add(fragment)
    mFragmentTitleList.add(title)
}

override fun getPageTitle(position: Int): CharSequence {
    return mFragmentTitleList[position]
}

这是我的片段

class MainFragment : Fragment() {
private val tabFrag by lazy { tab_frag }
private val pagerFrag by lazy { pager_frag }

private lateinit var pagerAdapter: FragmentAdapter

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_main, container, false)
}

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    pagerAdapter = FragmentAdapter(childFragmentManager)
    pagerAdapter.addFragment(FirstFragment(), "First")
    pagerAdapter.addFragment(ScndFragment(), "Second")
    pagerAdapter.addFragment(ThirdFragment(), "Third")
    pagerFrag.adapter = pagerAdapter
    tabFrag.setupWithViewPager(pagerFrag)
    tabFrag.setOnTabSelectedListener(OnTabCustomSelectedListener(context, tabFrag))
    val tabCount = tabFrag.tabCount
    for (i in 0 until tabCount) {
        val tab = tabFrag.getTabAt(i)
        if (tab != null) {
            val tabTextView = LayoutInflater.from(context).inflate(R.layout.item_tab_text, tabFrag, false) as TextView
            tabTextView.text = tab!!.text
            tabTextView.setTextAppearance(context,
                    if (i == 0) {
                        R.style.TextAppearance_Tabs_Selected
                    } else {
                        R.style.TextAppearance_Tabs
                    })
            tab.customView = tabTextView
        }
    }
}

0 个答案:

没有答案