我目前正在开发一个简单的应用来显示闪存卡。目前,我正在使用带有代表卡片的片段的ViewPager,以便在卡片之间滑动。但是,我想在闪存卡下方设置一组静态按钮,以便进行收藏,翻转存储卡以及重新整理卡片组之类的操作。是否可以通过父视图与ViewPager中当前显示的片段进行交互?
活动代码(改编自ViewPager的教程):
class ViewFlashCardsActivity : FragmentActivity(),
FlashCardFragment.OnFragmentInteractionListener{
private lateinit var mPager: ViewPager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_view_book)
// Instantiate a ViewPager and a PagerAdapter.
mPager = findViewById(R.id.pager)
// The pager adapter, which provides the pages to the view pager widget.
val pagerAdapter = FlashCardPagerAdapter(supportFragmentManager)
mPager.adapter = pagerAdapter
}
override fun onBackPressed() {
if (mPager.currentItem == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
super.onBackPressed()
} else {
// Otherwise, select the previous step.
mPager.currentItem = mPager.currentItem - 1
}
}
private inner class FlashCardPagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) {
val flashCards = ArrayList<FlashCardFragment>()
// Static for now for testing
init {
flashCards.add(FlashCardFragment.newInstance(0, "Flash card 1", "Back of flash card 1"))
flashCards.add(FlashCardFragment.newInstance(1, "Flash card 2", "Back of flash card 2"))
flashCards.add(FlashCardFragment.newInstance(2, "Flash card 3", "Back of flash card 3"))
}
override fun getCount(): Int = flashCards.count()
override fun getItem(position: Int): Fragment = flashCards.get(position)
}
该活动的XML只是具有以下某些按钮的ViewPager。