Last active
December 20, 2019 16:09
-
-
Save apksherlock/e2a57db7c8ae16425ac0f5a5e7932943 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MainActivity : AppCompatActivity() { | |
private lateinit var viewPager: ViewPager2 | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
viewPager = findViewById(R.id.my_view_pager) | |
val tabLayout = findViewById<TabLayout>(R.id.tabs) | |
val pagerAdapter = ScreenSlidePagerAdapter(this) | |
viewPager.adapter = pagerAdapter | |
TabLayoutMediator(tabLayout, viewPager) { tab, position -> | |
when (position) { | |
0 -> tab.text = "Home" | |
1 -> tab.text = "School" | |
} | |
}.attach() //this replaces the tabLayout.setupWithViewPager() from ViewPager API | |
} | |
override fun onBackPressed() { | |
if (viewPager.currentItem == 0) { | |
super.onBackPressed() //if I'm in the first Fragment just go back | |
} else { | |
viewPager.currentItem = viewPager.currentItem - 1 //just slide to the first Fragment | |
} | |
} | |
private inner class ScreenSlidePagerAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) { | |
override fun getItemCount(): Int = 2 //because I have two Fragments | |
override fun createFragment(position: Int): Fragment = if (position == 0) { | |
HomeFragment() | |
} else { | |
SchoolFragment() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment