'Change android tab programmically

I'am using Tablayout with view pager,

in some cases i want change the first tab, but i can't figure it out

how i implemended:

    val tabLayout=view.findViewById<TabLayout>(R.id.tabLayout)
    val viewPager=view.findViewById<ViewPager2>(R.id.viewPager)

    viewPager.adapter=ViewPagerAdapter(requireActivity())

    TabLayoutMediator(tabLayout,viewPager){tab,position ->

        tab.text=if(position==1){getString(R.string.one)}else{getString(R.string.two)}
    }.attach()

    if(flag){
        viewPager.currentItem=1
    }

with this implementation tab indicator change correctly but fragment not changes.

how can i figure it out, thanks in advance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source