简体   繁体   中英

How to pass data from activity to Fragment which is inside viewpager

I have one tab activity that contain 3 tabs.

I have one edittext and button in my activity, one textview in fragments.

Whenever I need to change the fragment textview I simply add some text in edittext and click the button after. That text should appear in the fragment. Here I am not able to use setArguments .

Otto's EventBus to the rescue. I had exactly this situation to handle. In my case I needed to trigger a fragment change inside a viewpager with locked swipes. So

Gradle:

// EventBus
implementation 'org.greenrobot:eventbus:3.0.0'

Make an event which will be passed from the activity to the fragment

public class FragmentChangeEvent {
public int fragmentToBeChanged;
 //here you can define variables of your choosing, just make sure you're including them into the constructor of the event.
public FragmentChangeEvent(int fragmentToBeChanged) {
    this.fragmentToBeChanged = fragmentToBeChanged;
    }
}

Trigger the event from the activity

  EventBus.getDefault().post(new FragmentChangeEvent(1));

And finally make your fragment aware of the bus and the events

@Subscribe(threadMode = ThreadMode.MAIN)
public void onChangeFragmentEvent(FragmentChangeEvent event) {
  //do your work here.
   }
}

If you are using ViewPager to render the fragment use this code in your parent Activity.

if(viewPager.getCurrentItem() == 1) //First fragment
{
     FragmentOne frag1 = (FragmentOne)viewPager.getAdapter().instantiateItem(viewPager, viewPager.getCurrentItem());
     frag1.textview.setText(yourText);
}

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