Call fragment method from android activity tab

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/

In this way, tabs are implemented using fragments that are processed using TabsPagerAdapterthat extends FragmentPagerAdapter.

However, I cannot call the method in one of the fragments from my main action.

I want to call this method when my main action receives a message. In particular, I need to update the fragment interface when this message is received. But I'm not sure how to correctly identify the fragment, since it was not declared in xml and therefore does not have the / id tag.

I was hoping someone could help me find a better way to do this.

+4
source share
1 answer

first create the whole fragment in the onCreatemethod Activityand add it tomMyFrag

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 the 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);
}

}

therefore, when you want to call a method from activity to fragment, say 1, do the following:

mMyFrag.get(1).yourMethod();
+1
source

All Articles