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
        // ...
    }
}

2 Answers 2

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?

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();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.