2

I have an activity that use ViewPagerIndicator. I have implement a class PagerAdapter that extends FragmentPagerAdapter, to set the fragment on the page.

In my activity this is my code:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mAdapter = new PagerAdapter(getSupportFragmentManager());
    mPager = (ViewPager)findViewById(R.id.pager);
    mPager.setAdapter(mAdapter);
    mIndicator = (CirclePageIndicator)findViewById(R.id.indicator);

    mIndicator.setViewPager(mPager);
}

My activity also have a menu options, with a option "A" . When user click on option menu and choose "A", my activity want to call a method of the current fragment. But how activity know the currentFragment?

I want this:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case R.id.A:
            getCurrentFragment.Method(); //Method is the method that want to execute
        // ...
    }
}
Paolo Moretti
  • 47,973
  • 21
  • 95
  • 89
esoni
  • 1,272
  • 3
  • 23
  • 35

2 Answers2

0

Yes, you can get current fragment:

getSupportFragmentManager().findFragmentByTag("android:switcher:"+R.id.viewpager+":0");

Look these questions and answers for details:

Update data in ListFragment as part of ViewPager

Is it possible to access the current Fragment being viewed by a ViewPager?

Community
  • 1
  • 1
kolobok
  • 3,212
  • 3
  • 32
  • 49
0

You answered your question yourself. What is wrong. I had the same problem. I had a button and i wanted to do different tasks in different fragments. I used this code:

indicator.setOnPageChangeListener(new OnPageChangeListener() {
@Override
        public void onPageSelected(final int position) {
            // TODO Auto-generated method stub

            btn_calculate.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    switch (position) {
                        case 0:
                            Fragment0.calculator();
                            break;
                        case 1:
                            Fragment1.calculator();
                            break;
                        case 2:
                            Fragment2.calculator();
                            break;

                    }

                }
            });

And use this code to access to your fragments:

YourownFragment fragment = 
      (YourownFragment) getSupportFragmentManager().findFragmentByTag(
                   "android:switcher:"+R.id.viewpager+":0");

and also u can use this code to access to the current fragment:

int current_item = mPager.getCurrentItem();
Dariush Malek
  • 804
  • 1
  • 5
  • 12