Send values from ViewPager Activity to a Fragment by bundle

后端 未结 2 1868
忘了有多久
忘了有多久 2020-12-09 05:32

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 th

相关标签:
2条回答
  • 2020-12-09 06:13

    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.

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_screen_slide);
        Bundle bundle = new Bundle();
        bundle.putInt("SIDE",2);
        mPager = (ViewPager)findViewById(R.id.pager);
        mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager(), bundle);
        mPager.setAdapter(mPagerAdapter);
    }
    
    
    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter{
    
        private final Bundle fragmentBundle;
    
        public ScreenSlidePagerAdapter(FragmentManager fm, Bundle data){
            super(fm);
            fragmentBundle = data;
        }
    
        @Override
        public ScreenSlidePageFragment getItem(int arg0) {
            final ScreenSlidePageFragment f = new ScreenSlidePageFragment();
            f.setArguments(this.fragmentBundle);
            return f;
        }
    
        @Override
        public int getCount() {
            return  NUM_PAGES;
        }
    }
    

    Fragment

    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);
        final Bundle args = getArguments();
        final int side = args.getInt("SIDE");
    }
    
    0 讨论(0)
  • 2020-12-09 06:27

    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:

    public void doSomething(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)
    MyFragment fragment = (MyFragment) mAdapter.getItem(0);
    fragment.doSomething("some-value");
    
    0 讨论(0)
提交回复
热议问题