4

I have an android app that has several tabs. To create the tabs I used the following tutorial:

http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/

So the tabs are implemented using Fragments that are handled by TabsPagerAdapter which extends FragmentPagerAdapter.

However I have having trouble calling a method in one of the fragments from my main activity.

I want to call this method when my main activity receives a message. More specifically I need to update the UI of the fragment when this message is received. But I am not sure how to properly identify the fragment as it was not declared in an xml and therefore does not have a tag/id.

I was hoping that somebody would be able to help me find the best way to do this.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
edbert
  • 125
  • 1
  • 5
  • 16
  • possible duplicate of [Calling method inbetween Fragments which are in tabs](http://stackoverflow.com/questions/14202662/calling-method-inbetween-fragments-which-are-in-tabs) – Víctor Albertos Sep 02 '14 at 17:40
  • how many fragments do you have? – mmlooloo Sep 02 '14 at 17:45
  • Thank you for pointing that out. However that question is a little different. It describes how to call a method from a fragment within another fragment. What I was hoping to find out is how to call a method from a fragment in the parent activity. This is because messages are received in my activity and not in the fragment. Alternatively if there was a way to change the UI of a fragment from the parent activity this would also work for me. – edbert Sep 02 '14 at 17:50
  • I have three fragments, however for the purpose of this question you could assume that I only have one. I need to be able to update one of the fragments when a message is received by an activity – edbert Sep 02 '14 at 17:52
  • See my answer http://stackoverflow.com/questions/12739909/send-data-from-activity-to-fragment-in-android/38741476#38741476 – Noorul Dec 05 '16 at 11:18

1 Answers1

1

first create all of your fragment in onCreate method of Activity and add them to mMyFrag

ArrayList<MyFragment> mMyFrag = new ArrayList<MyFragment>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    for(int i=0; i<4; i++) {
        MyFragment fragment = MyFragment.newInstance(arg);
        mMyFrag.add(fragment);
   }
}

and change your adapter to :

private class MyPagerAdapter extends FragmentPagerAdapter {

private ArrayList<MyFragment> mMyFragList;

public MyPagerAdapter(FragmentManager fm, ArrayList<MyFragment> list) {
    super(fm);
    mMyFragList = list;
}

@Override
public int getCount() {
   return mMyFragList.size();
}

@Override
public int getItemPosition(Object object) {
    return POSITION_NONE;
}

@Override
public MyFragment getItem(int position) {
   return mMyFragList.get(position);
}

}

so when you want to call a method from activity to fragment say 1 do this:

mMyFrag.get(1).yourMethod();
mmlooloo
  • 18,937
  • 5
  • 45
  • 64