简体   繁体   中英

Android ViewPager - floating action button clicks

I have the ViewPager and the floating action button in my MainActivity . Each fragment in the ViewPager is a 6x6 GridLayout . On button click, I want to start animation moving ImageView inside the GridLayout . Start and target positions are predefined in the list.

mViewPager = findViewById(R.id.pager)
mViewPager.adapter = mSectionsPagerAdapter
mViewPager.currentItem = currentFragment

val fab: View = findViewById(R.id.floatingActionButton)
fab.setOnClickListener(object : View.OnClickListener {
    override fun onClick(v: View) {
      val c =  mViewPager.currentItem
      val fromView = grid.getChildAt(fromList[c]) as ImageView
      val toView = grid.getChildAt(toList[c]) as ImageView
      val anim = TranslateAnimation(0f, toView.x - fromView.x, 0f, toView.y - fromView.y).apply {
          duration = 500
          fillAfter = false
      }
      fromView.startAnimation(anim)
}

Animation works as expected, but the problem is that it works only on the first page. When I swap to other pages and click the button, nothing happens. When I get back to the first page, also nothing happens. Can someone explain why this is so? How do I fix it? Thank you.

If you are aware of how many "pages" you have in your application, you can set the offscreenpagesize . What happens is sometimes on swiping the pages out of focus, the context of those fragments could be lost.

viewPage.setOffscreenPageLimit(<number of fragments 'tabs'>);

View more details of this method here.

If you have several pages then do not use setOffscreenPageLimit

Try to add fab.setOnClickListener in each fragment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM