Monday 24 June 2013

Get current visible fragment page in a ViewPager

There are two ways to get current visible fragment page in ViewPager.

FIRST APPROACH

You can set a unique tag on each fragment page like below

etSupportFragmentManager().beginTransaction().add(myFragment, "Some Tag").commit();

then retrieve the fragment page

getSupportFragmentManager().findFragmentByTag("Some Tag");

 You need to keep track of the string tags and link them with the fragments. Use a HashMap to store each tag along with the current page index, which is set at the time when the fragment page is instantiated.


MyFragment myFragment = MyFragment.newInstance();
mPageReferenceMap.put(index, "Some Tag");
getSupportFragmentManager().beginTransaction().add(myFragment, "Some Tag").commit();

To get current visible page's tag you need to call

int index = mViewPager.getCurrentItem();
String tag = mPageReferenceMap.get(index);

and then to get current visible fragment call

Fragment myFragment = getSupportFragmentManager().findFragmentByTag(tag);


SECOND APPROACH

Second approach is also similar to the first one, here also we have to keep track of all the active fragments. In this case, you keep track of the fragments in the FragmentStatePagerAdapter.

public Fragment getItem(int index) {
    Fragment myFragment = MyFragment.newInstance();
    mPageReferenceMap.put(index, myFragment);
    return myFragment;
}

You should not keep the reference of inactive fragments, to remove inactive fragments from mPageReferenceMap we need to implement FragmentStatePagerAdapter's destoryItem(...) method and do like below.

public void destroyItem(View container, int position, Object object) {
    super.destroyItem(container, position, object);
    mPageReferenceMap.remove(position);
}

and to access the current visible fragment page, you then call


int index = mViewPager.getCurrentItem();
MyAdapter adapter = ((MyAdapter)mViewPager.getAdapter());
MyFragment fragment = adapter.getFragment(index);

MyAdapter's getFragment(int) method should be like this

public MyFragment getFragment(int key) {
    return mPageReferenceMap.get(key);
}

I prefer the second approach.

130 comments:

  1. Third option:

    Override setPrimaryItem from your FragmentPagerAdapter or FragmentStatePagerAdapter, argument object is your current fragment:

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
    if (mCurrentFragment != object) {
    mCurrentFragment = (Fragment) object;
    }
    super.setPrimaryItem(container, position, object);
    }

    ReplyDelete
  2. That is for to get the which fragment we are in?

    ReplyDelete
  3. I have totally 20 fragments . I need to show 1/20,2/20 like that any one helps me?

    ReplyDelete
    Replies
    1. Add fragments like this...


      public class FragmentsPagerAdapter extends FragmentStatePagerAdapter {

      int numberOftabs;
      Context context;
      FragmentManager fm;
      Map fragmentsMap = new HashMap<>();

      public FragmentsPagerAdapter(@NonNull FragmentManager fm, int numberOftabs, Context context) {
      super(fm);
      this.fm = fm;
      this.numberOftabs = numberOftabs;
      this.context = context;
      }

      public FragmentsPagerAdapter(@NonNull FragmentManager fm, int behavior, int numberOftabs) {
      super(fm, behavior);
      this.numberOftabs = numberOftabs;
      }


      @NonNull
      @Override
      public Fragment getItem(int position) {
      Fragment fragment;
      switch (position) {
      case 0:
      fragment = new FirstFragment(context);
      break;
      case 1:
      fragment = new SecondFragment(context);
      break;
      case 2:
      fragment = new ThirdFragment(context);
      break;
      default:
      throw new IllegalStateException("fragment is null at " + position);
      }
      fragmentsMap.put(position, fragment);
      return fragment;
      }

      @Override
      public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
      super.destroyItem(container, position, object);
      fragmentsMap.remove(position);
      }

      public Fragment getFragment(int position) {
      return fragmentsMap.get(position);
      }

      @Override
      public int getCount() {
      return numberOftabs;
      }

      }



      Get fragments in activity likes this....

      SecondFragment secondFragment = (SecondFragment) fragmentsfragmentsPagerAdapter.getFragment(1);
      secondFragment.updateFragment();

      Tell me if not working.

      Delete
  4. HEllo. Where and how do you declare "mCurrentFragment "?

    ReplyDelete
  5. @Juan Corso : mCurrentFragment :

    private Fragment mCurrentFragment;

    public Fragment getCurrentFragment() {
    return mCurrentFragment;
    }

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it.
    Click here:
    angularjs training in tambaram
    Click here:
    angularjs6 Training in Chennai

    ReplyDelete
  8. This is a terrific article, and that I would really like additional info if you have got any. I’m fascinated with this subject and your post has been one among the simplest I actually have read.
    Click here:
    Microsoft azure training in sollinganallur

    ReplyDelete
  9. Great content thanks for sharing this informative blog which provided me technical information keep posting.
    Click here:
    python training in velachery
    Click here:
    python training in OMR

    ReplyDelete
  10. This blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.Thank you for this blog. This for very interesting and useful.

    rpa Training in Chennai

    rpa Training in bangalore

    rpa Training in pune

    blueprism Training in Chennai

    blueprism Training in bangalore

    blueprism Training in pune

    iot-training-in-chennai

    ReplyDelete
  11. Excellent blog, I wish to share your post with my folks circle. It’s really helped me a lot, so keep sharing post like this
    Blueprism training in marathahalli


    AWS Training in chennai

    AWS Training in bangalore



    ReplyDelete
  12. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    Devops Training in Chennai
    Devops Training in Bangalore

    ReplyDelete
  13. Pc to free business calls cost money. Even then some VoIP providers let you make free calls to landline or mobile phones. Who foots the bill?

    ReplyDelete
  14. This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. 

    best rpa training in chennai |
    rpa training in chennai |
    rpa training in bangalore
    rpa training in pune | rpa online training

    ReplyDelete
  15. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    Qlikview Training From India

    Cognos Training From India

    Sap Pp Training From India

    ReplyDelete
  16. Superb. I really enjoyed very much with this article here. Really it is an amazing article I had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article. thank you for sharing such a great blog with us.

    Data Science training in rajaji nagar | Data Science with Python training in chenni
    Data Science training in electronic city | Data Science training in USA
    Data science training in pune | Data science training in kalyan nagar

    ReplyDelete
  17. Well done! Pleasant post! This truly helps me to discover the solutions for my inquiry. Trusting, that you will keep posting articles having heaps of valuable data. You're the best! 

    angularjs Training in chennai
    angularjs-Training in pune

    angularjs-Training in chennai

    angularjs Training in chennai

    angularjs-Training in tambaram

    angularjs-Training in sholinganallur

    ReplyDelete
  18. Awesome..You have clearly explained.it is very simple to understand.it's very useful for me to know about new things..Keep blogging.Thank You...
    aws online training
    aws training in hyderabad
    aws online training in hyderabad

    ReplyDelete
  19. You made such an interesting piece to read, giving every subject enlightenment for us to gain knowledge. Thanks for sharing the such information with us
    apple iphone service center in chennai | apple iphone service center in chennai | apple iphone service center in chennai

    ReplyDelete
  20. "Does your blog have a contact page? I’m having problems locating it but, I’d like to shoot you an email. I’ve got some recommendations for your blog you might be interested in hearing.
    "
    apple service center chennai | Mac service center in chennai | ipod service center in chennai | Apple laptop service center in chennai

    ReplyDelete
  21. This is an excellent post I seen thanks to share it. It is really what I wanted to see hope in future you will continue for sharing such a excellent post.
    moto service centre chennai
    moto service center
    motorola service center
    motorola service center near me

    ReplyDelete
  22. Really great post, I simply unearthed your site and needed to say that I have truly appreciated perusing your blog entries.
    angularjs online training

    apache spark online training

    informatica mdm online training

    devops online training

    aws online training

    ReplyDelete
  23. This comment has been removed by the author.

    ReplyDelete
  24. Có lẽ cần phải trải qua tuổi thanh xuân( Phương pháp học toán tư duy ) mới có thể hiểu được tuổi xuân là khoảng thời gian ta( dạy trẻ học toán tư duy ) sống ích kỷ biết chừng nào. Có lúc nghĩ, sở dĩ tình yêu cần phải đi một vòng tròn lớn như vậy, phải trả một cái giá quá đắt như thế,( Làm cho trẻ thích học toán ) là bởi vì nó đến không đúng thời điểm. Khi có được( Toán mầm non ) tình yêu, chúng ta thiếu đi trí tuệ. Đợi đến khi( Bé học đếm số ) có đủ trí tuệ, chúng ta đã không còn sức lực để yêu một tình yêu thuần khiết nữa.

    ReplyDelete
  25. Vanskeligheter( van bi ) vil passere. På samme måte som( van điện từ ) regnet utenfor( van giảm áp ) vinduet, hvor nostalgisk( van xả khí ) er det som til slutt( van cửa ) vil fjerne( van công nghiệp ) himmelen.

    ReplyDelete
  26. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    blue prism Training in Electronic City

    ReplyDelete
  27. Pest control services Chennai is a dedicated service solution to all your pest and insect troubles in Chennai.
    Pest control services in chennai.
    Pest control in chennai.
    Pest control services near me.

    ReplyDelete
  28. iPhone Service center in Bangalore No. 1 Leaders Awesome Services On-time, Every time!
    iPhone Service Center in Bangalore
    Apple Service center in Bangalore
    Apple Service Center in Bangalore

    ReplyDelete
  29. Mi Service Center in Chennai

    Mi Service Center in Chennai No. 1 Leaders Awesome Services On-time, Every time!
    Mi Service Center in Chennai
    Redmi Service Center in Chennai
    Mi Service Center in Chennai

    ReplyDelete
  30. This comment has been removed by the author.

    ReplyDelete
  31. OnePlus Service Center in Chennai

    OnePlus Service Center in Chennai No. 1 Smart Service On Time, Every Time
    OnePlus Service Center in Chennai
    OnePlus Service Center in Chennai
    OnePlus Service Center in Chennai

    ReplyDelete
  32. Moto service center in Chennai
    Leading Motorola Service Center In Chennai. Fast & Reliable Services On-time, Every time!
    Moto service center in Chennai
    Motorola Service Center In Chennai
    Motorola Service Center In Chennai

    ReplyDelete
  33. Iphone service center in Chennai

    Iphone service Center in Chennai offers you best quality of Services On-time, Every time!
    IPhone Service Center in Chennai
    Apple Iphone Service center in Chennai
    Apple Service Center in Chennai
    Apple Service center in Chennai
    IPhone Service Center in Chennai

    ReplyDelete
  34. LG Mobile Service Center In Chennai

    LG Mobile Service Center In Chennai. Providing Fast, Honest, Reliable & Cost Effective Service Solutions To The LG Mobile Users.
    LG Mobile Service Center In Chennai

    ReplyDelete
  35. Sony Mobile Service Center In Chennai
    Sony Servicing by No. 1 Leaders Awesome Services On-time, Every time!
    Sony Mobile Service Center In Chennai

    ReplyDelete
  36. Nokia Mobile Service Center In Chennai
    Nokia Mobile Service Center In Chennai. Providing Fast, Honest, Reliable & Cost Effective Service Solutions to The Nokia Mobile Users.
    NOkia Mobile Service Center In Chennai

    ReplyDelete
  37. Honor service center in Chennai

    Honor Service Center in Chennai for the Best & Right Place to service your Honor mobile phone.
    Honor Service Center in Chennai

    ReplyDelete
  38. Ipad service center in Chennai

    Ipad service Center in Chennai offers you best quality of Services On-time, Every time!
    Ipad Service Center in Chennai

    ReplyDelete
  39. Apple Imacbook Service Center in Chennai

    Apple Laptop Service Center in Chennai offers you best quality of Services On-time, Every time!
    Apple Laptop Service Center in Chennai

    ReplyDelete
  40. Awesome Post!!!

    Redmi Service Center in Chennai

    Redmi Service Center in Chennai No. 1 Leaders Awesome Services On-time, Every time!
    Redmi Service center in chennai
    Mi Service Center in Chennai
    Mi Service Center in Chennai

    ReplyDelete
  41. WOW Great Post!!!

    Apple iPhone Service Center in Chennai

    Chennai No-1 Apple iPhone Service Center in Chennai
    Apple iPhone Service Center in Chennai
    Iphone Service Center in Chennai
    Iphone Service Center in Chennai
    Apple Service Center In Chennai
    Apple Service Center In Chennai

    ReplyDelete
  42. click here for more info.
    ..........................................................

    ReplyDelete
  43. Oneplus Service Center in Bangalore

    Oneplus Repair Service Center in Bangalore. For the finest service and fastest delivery for your Oneplus mobile, visit us! Go home a happy customer! Connect with us!!

    Oneplus Mobile Service Center in Bangalore

    ReplyDelete
  44. Oppo Service Center in Bangalore

    OPPO Service Center in Bangalore is the best OPPO Service Center in Bangalore. We can fix all OPPO devices at low cost with best quality.
    Oppo Repair Center in Bangalore- All our OPPO care technicians has 10+ years experience in the mobile care fix industry

    Oppo repair center in bangalore

    ReplyDelete
  45. Effective blog with a lot of information. I just Shared you the link below for ACTE .They really provide good level of training and Placement,I just Had Android Classes in ACTE , Just Check This Link You can get it more information about the Android course.

    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  46. Excellent read, Positive site, where did u come up with the information on this posting? I have read a few of the articles on your website now, and I really like your style.keep update
    Ai & Artificial Intelligence Course in Chennai
    PHP Training in Chennai
    Ethical Hacking Course in Chennai Blue Prism Training in Chennai
    UiPath Training in Chennai

    ReplyDelete
  47. Thanks a lot for sharing such a good source with all, i appreciate your efforts taken for the same. I found this worth sharing and must share this with all.


    AWS training in Chennai

    AWS Online Training in Chennai

    AWS training in Bangalore

    AWS training in Hyderabad

    AWS training in Coimbatore

    AWS training

    ReplyDelete
  48. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information
    java training in chennai

    java training in omr

    aws training in chennai

    aws training in omr

    python training in chennai

    python training in omr

    selenium training in chennai

    selenium training in omr

    ReplyDelete
  49. Android apps are applications that have been typically devised with the Java programming language, in collaboration with the Android Software Development Kit. However, there are other development kits such as Android NDK or indigenous tools for extensions or apps in C/C++. There is a visual setting which is known as Google App Inventor which the beginners and trainee developers use. spy phone app

    ReplyDelete
  50. This information is impressive..I am inspired with your post writing style & how continuously you describe this topic.

    Apache Spark Training in Pune
    Python Classes in Pune

    ReplyDelete
  51. The popularity of clean technology is rapidly growing: people are realizing that by being eco-friendly and applying these principles to their companies, they are able to deliver quality products and services, while promoting the protection of the planet, its natural resources and the importance behind these efforts. As technology continues to evolve and adapt to our needs, many agree that clean technology is tomorrow's technology. phone tracker

    ReplyDelete
  52. Rattling clean web site , appreciate it for this post. Mega888 android and ios

    ReplyDelete
  53. hanks for the informative article. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.salesforce training in chennai

    software testing training in chennai

    robotic process automation rpa training in chennai

    blockchain training in chennai

    devops training in chennai

    ReplyDelete
  54. That’s why you have to have effective web based business home keep when it comes to taking items right your individual web-based online business. cash 토토사이트

    ReplyDelete
  55. Some of these solutions come free, while others require a small subscription fee. However, the price of this software solution is worth the peace of mind it can provide. Source to know about spy phone.

    ReplyDelete
  56. Rattling clean web site , appreciate it for this post. 918kiss android and ios

    ReplyDelete
  57. The Southwest Florida climate is very hard on security cameras. The humidity, driving rains, extreme heat, power surges and salty air can cause security cameras or the Digital Video Recorder (DVR) to stop functioning unexpectedly. Unfortunately, many times these problems are not discovered until after an event occurred. diy homemade spy camera from old mobile phone camera

    ReplyDelete
  58. very nice post, i certainly adore this web site, continue it 512jbb

    ReplyDelete
  59. very good post, i definitely love this website, carry on it bet188

    ReplyDelete
  60. I’d must examine with you here. Which is not something I usually do! I take pleasure in reading a post that will make folks think. Additionally, thanks for permitting me to remark! buy steroids

    ReplyDelete
  61. bar stools that are made from stainless steel are the best because they don’t tarnish often,, buy steroids

    ReplyDelete
  62. Thank you for sharing. This is a very nice blog. parrots for sale

    ReplyDelete
  63. I dugg some of you post as I thought they were handy very helpful lovebirds for sale

    ReplyDelete
  64. I’m not sure exactly why but this website is loading extremely slow for me. Is anyone else having this issue or is it a issue on my end? I’ll check back later and see if the problem still exists. Build custom apps development

    ReplyDelete
  65. Hi there, I found your blog via Google while looking for a related topic, your site came up, it looks great. I’ve bookmarked it in my google bookmarks. rad application builder

    ReplyDelete
  66. Perfect work you have done, this site is really cool with wonderful info . quality link building

    ReplyDelete
  67. Hello! I would like to offer a enormous thumbs up for your fantastic information you’ve got here during this post. I will be returning to your blog to get more soon. buy sugar paste

    ReplyDelete
  68. my baby enjoys playing on the baby swing, baby swings can really make your baby happy- 먹튀검증 먹튀폴리스

    ReplyDelete
  69. An impressive share, I recently with all this onto a colleague who was simply doing little analysis for this. And hubby actually bought me breakfast since I found it for him.. smile. So let me reword that: Thnx for your treat! But yeah Thnkx for spending the time to talk about this, I find myself strongly about this and adore reading much more about this topic. Whenever possible, as you become expertise, might you mind updating your blog site with additional details? It is highly great for me. Massive thumb up just for this article! buy steroids online

    ReplyDelete
  70. A very exciting go through, I may not agree completely, but you do make some really legitimate factors. steroids for sale

    ReplyDelete
  71. it is always a good idea to go green because we always want to help the environment,. buy hgh

    ReplyDelete
  72. When I originally commented I clicked the -Notify me when new surveys are added- checkbox and today whenever a comment is added I receive four emails using the same comment. Possibly there is however you can eliminate me from that service? Thanks! hcg for sale

    ReplyDelete
  73. It’s a shame you don’t have a donate button! I’d without a doubt donate to this brilliant blog! I suppose for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to fresh updates and will share this blog with my Facebook group. Chat soon! buy clenbuterol

    ReplyDelete
  74. i really love a good read like, please keep us updated with info. human growth hormone for sale

    ReplyDelete
  75. Great info – Gulvafslibning | Kurt Gulvmand I’m inquisitive to discover what blog platform you’re utilizing? We are experiencing some minor safety issues with my latest blog thus I’d wish to discover something a lot more risk-free. Are there some suggestions! Take care Online Website Builder steroids for sale

    ReplyDelete
  76. Tremendous review! Would like had this analyzing. I’m hoping to find out a lot more of you. I know you may have beneficial details combined with prospect. I’m just seriously contented from this information and facts. Therapy

    ReplyDelete
  77. It’s a shame you don’t have a donate button! I’d without a doubt donate to this brilliant blog! I suppose for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to fresh updates and will share this blog with my Facebook group. Chat soon! Grief therapy

    ReplyDelete
  78. Cruise is back and this time he brought he comedic chops with him. the jacket from drive

    ReplyDelete
  79. I can’t really help but admire your blog, your blog is so adorable and nice .     red leather trench coat

    ReplyDelete
  80. It’s my job to dont usually post on many Blogs, still I recently has to say thank you maintain the astonishing work. Ok unfortunately it is time to get at school. nidroy devient

    ReplyDelete
  81. The first thing that always comes in mind whenever it comes to establishment of a mobile presence for your business there are things that will come in mind. The first thing that comes to mind is probably creating a mobile application that users may use to download or alternatively a mobile website. At first glance, both mobile websites and mobile apps may look the same and getting to decide which one to go for depends on a number of issues. originally us

    ReplyDelete
  82. Supradyn Tablet is use in very easy in people. this tablet is multivitamin

    ReplyDelete

  83. fcs ration card list is the most popular website in uttar pradesh govt

    ReplyDelete
  84. Nice information, this is will helpfull a lot, Thank for sharing, Keep do posting i like to follow this.
    Best IELTS Institute in Ambala
    Best IELTS Coaching in Ambala

    ReplyDelete
  85. Great post really useful information. We are the leading web development company in chennai. Hire our web design company in chennai today for best web design services in chennai.

    ReplyDelete
  86. Are you looking for a way to watch the latest Pathan movie in high-quality and for free? Look no further! Here we provide you with the best options to Pathan Full Movie Download 4K, HD, 1080p 480p, 720p in Hindi quality for free in Hindi. We have compiled a list of reliable sources that offer the highest quality streaming and downloading services. So get ready to dive into the world of Pathan with this ultimate guide on how to download it for free !

    ReplyDelete
  87. t was very useful for me. Keep sharing such ideas in the future as well. i just want to share with you the best digital marketing company in surat

    ReplyDelete
  88. Thanks for sharing this wonderful information.Buy Silver Coins

    ReplyDelete
  89. Thank you for sharing such valuable information. Your blog always provides a fresh perspective, and I find it both informative and enjoyable to read. Keep up the great work!" AWS Training in Pune

    ReplyDelete