Skip to content Skip to sidebar Skip to footer

Send Values From Viewpager Activity To A Fragment By Bundle

I have an ViewPager Activity that call the fragment that represent the slide layout. What i need is pass values from activity to fragment by bundle. How i can do this? I try pass

Solution 1:

You have to set your Bundle through setArguments() method, not the intent. If you have a ViewPager, you can pass your arguments to the PagerAdapter, and set the arguments when the Fragment is being instantiated.

I don't get how your SIDE is calculated and what does it mean, so I show the general ide.

@OverrideprotectedvoidonCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_screen_slide);
    Bundlebundle=newBundle();
    bundle.putInt("SIDE",2);
    mPager = (ViewPager)findViewById(R.id.pager);
    mPagerAdapter = newScreenSlidePagerAdapter(getSupportFragmentManager(), bundle);
    mPager.setAdapter(mPagerAdapter);
}


privateclassScreenSlidePagerAdapterextendsFragmentStatePagerAdapter{

    privatefinal Bundle fragmentBundle;

    publicScreenSlidePagerAdapter(FragmentManager fm, Bundle data){
        super(fm);
        fragmentBundle = data;
    }

    @Overridepublic ScreenSlidePageFragment getItem(int arg0) {
        finalScreenSlidePageFragmentf=newScreenSlidePageFragment();
        f.setArguments(this.fragmentBundle);
        return f;
    }

    @OverridepublicintgetCount() {
        return  NUM_PAGES;
    }
}

Fragment

@OverridepublicvoidonCreate(Bundle state) {
    super.onCreate(state);
    finalBundleargs= getArguments();
    finalintside= args.getInt("SIDE");
}

Solution 2:

This might not be the solution you are exactly asking for but it is what I do and it may help someone:

Create a public method in your fragment:

publicvoiddoSomething(String myValue){
     // Do stuff in your fragment with myValue
}

In your activity, get the fragment from your Adapter. You know which fragment it is based on order it was added in. Execute your fragment method, passing in your variable(s):

// Get FriendsFragment (first fragment)MyFragmentfragment= (MyFragment) mAdapter.getItem(0);
fragment.doSomething("some-value");

Post a Comment for "Send Values From Viewpager Activity To A Fragment By Bundle"