Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling method from Fragment in ViewPager

I have a ViewPager with some Fragments inside. When creating each Fragment I call constructor where I pass name of this Fragment:

 public KwejkFragment(String tagName)
    {
        this.fragmentTag = tagName;
    }

In MainActivity ofcourse I create Adapter and ViewPager instance. Then I set listener of ViewPager:

mPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {

                FragmentManager fm = getSupportFragmentManager();

                Fragment fr = mAdapter.getItem(position);

                if(fr.equals(KwejkFragment.class))
                {
                    (KwejkFragment) fr.refresh(); //I'm trying to call method here for example showMeSomething() but it is unavailable.
                }

            }

And here I'd like to:

1)Get current visible Fragment in PagerView

2)Call specified method of this Fragment

How to do this?

like image 716
Darek Avatar asked Feb 14 '15 00:02

Darek


1 Answers

First make the method in the fragment to public and then use the following code

mPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {

                FragmentManager fm = getSupportFragmentManager();

                Fragment fr = mAdapter.getItem(position);

                if(fr instanceOf KwejkFragment))
                {
                     fr.refresh(); 
                }

            }

Put the debugger in the refresh method and check whether it is getting called or not.

This code will work. Enjoy :)

like image 55
Fahim Avatar answered Oct 16 '22 17:10

Fahim