简体   繁体   中英

Send data from Activity to fragment with ViewPager

I have got aplication with three screens(3 fragments and viewPager), and now I want to send for example String from Activity to FragmentA but I don't know how.

This is my Activity class with pager Adapter

public class MainActivity extends FragmentActivity {
ViewPager viewPager;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    viewPager= (ViewPager) findViewById(R.id.pager);
    viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));

}

}

class MyAdapter extends FragmentPagerAdapter{

public MyAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int arg0) {

    Fragment fragment=null;
    if(arg0==0){
        fragment=new FragmentA();


    }
    if(arg0==1){
        fragment=new FragmentB();


    }
    if(arg0==2){
        fragment=new FragmentC();


    }
    return fragment;
}

@Override
public int getCount() {
    return 3;
}

You can use the EventBus library or write something similar yourself, but the best option is to learn the correct and accepted methods of communication between components.

If you want to pass the data (String in your case) before the ViewPager initialized you can pass it via argumnents, here you can find a good example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM