Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: ViewPager FragmentStatePagerAdapter get current View

Question: How to get current View of a ViewPager FragmentStatePagerAdapter?

  1. I have spent almost 24 hours on this and searched everywhere for the fit solutions.
  2. Get current position is easy, I already got that. This is get current View.
  3. FragmentStatePagerAdapter is required, not PagerAdapter.

    • This solution suggested setTag and findViewWithTag via instantiateItem(View container, int position). This is for PagerAdapter.
    • However in FragmentStatePagerAdapter the instantiateItem has a ViewGroup param not View param: instantiateItem(**ViewGroup** container, int position)

So I hope it's not impossible, is it? Please help!

like image 687
jerrytouille Avatar asked Jul 05 '13 17:07

jerrytouille


1 Answers

You can use the setTag trick with the view you are returning in your instantiateItem method.

Here, I'm using a ViewPager with PagerAdapter, but I think this idea might work for you too.

So, when you are instantiating your views (in PagerAdapter the method is also instantiateItem(ViewGroup container, int position)), you should use setTag to your view.

Like this:
view.setTag("view" + position);
return view;

So, when you need the current view, you should do this: View view = (View) pager.findViewWithTag("view" + pager.getCurrentItem());, where pager is the ViewPager, which you can get passing it by params from your Activity to your adapter.

like image 116
Rodrigo Venancio Avatar answered Sep 24 '22 09:09

Rodrigo Venancio