Arnes
Arnes

Reputation: 402

Calling methods between fragments

This is very simplified problem that I have regarding to Fragments and calling methods between fragments. I have put in the code place where I think calling method should be. Correct me if I'm wrong or if you have right solution for my problem. MainFragment extends Fragment because it is not activity... I have navigation drawer so that is how it suppose to be... :)

public class MainFragment extends Fragment{

public MainFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_pager, container, false);

    adapter = new CategoriesPagerAdapter(getChildFragmentManager(),Titles,Numboftabs);

    pager = (ViewPager) rootView.findViewById(R.id.pager);
    pager.setAdapter(adapter);

    tabs = (SlidingTabLayout) rootView.findViewById(R.id.tabs);
    tabs.setDistributeEvenly(true);
    tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return getResources().getColor(R.color.tabsScrollColor);
        }
    });
    tabs.setViewPager(pager);


    Toolbar mToolbar = (Toolbar) getActivity().findViewById(R.id.toolbar_actionbar);
    final Spinner spinner_nav = (Spinner) mToolbar.findViewById(R.id.spinner_nav);
    spinner_nav.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            // ...here I need to call method "writeText()" in both fragments to update both TextViews also in both fragments (tabs)                
        }
    });     
}

public class CategoriesPagerAdapter extends FragmentStatePagerAdapter {

    CharSequence Titles[];
    int NumbOfTabs;

    public CategoriesPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
        super(fm);
        this.Titles = mTitles;
        this.NumbOfTabs = mNumbOfTabsumb;
    }

    @Override
    public Fragment getItem(int position) {
        if (position == 0) {
            Tab1Class tab1 = new Tab1Class();
            return tab1;
        } else if (position == 1) {
            Tab2Class tab2 = new Tab2Class();
            return tab2;
        } else {
            return null;
        }
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return Titles[position];
    }

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

Tab2Class:

public class Tab1Class extends Fragment {
TextView tv1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_tab1, container, false);
    tv1 = (TextView) rootView.findViewById(R.id.tv1);
    writeText();
}
public void writeText(){
    tv1.setText("TV1 text");
}
}

Tab1Class:

public class Tab2Class extends Fragment {
TextView tv2;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_tab2, container, false);
    tv2 = (TextView) rootView.findViewById(R.id.tv2);
    writeText();
}
public void writeText(){
    tv2.setText("TV2 text");
}
}

Upvotes: 1

Views: 79

Answers (2)

JoeyJubb
JoeyJubb

Reputation: 2321

Here's an alternative:

public class BlankFragment extends Fragment {

    public static final String ACTION_SOME_STUFF_HAPPENED = "stuff_happened_yo";
    public static final String EXTRA_STUFF = "this_is_stuff";


public static void notifyStuffHappening(Context context, String stuff){
    Intent intent = new Intent(ACTION_SOME_STUFF_HAPPENED);
    intent.putExtra(EXTRA_STUFF, stuff);

    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

private StuffHappenedReceiver mStuffListener;

public static class StuffHappenedReceiver extends BroadcastReceiver {


    final BlankFragment mFragment;

    public StuffHappenedReceiver(BlankFragment fragment) {
        this.mFragment = fragment;
        // listen for changes to the account we're using
        IntentFilter filter = new IntentFilter(ACTION_SOME_STUFF_HAPPENED);
        LocalBroadcastManager.getInstance(fragment.getContext()).registerReceiver(this, filter);
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        if (ACTION_SOME_STUFF_HAPPENED.equals(action)) {


            mFragment.someStuffHappened(intent.getStringExtra(EXTRA_STUFF));
        }

    }
}

private void someStuffHappened(String stringExtra) {

}

public BlankFragment() {
    // Required empty public constructor
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    mStuffListener = new StuffHappenedReceiver(this);
}

@Override
public void onDetach() {
    LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mStuffListener);
    mStuffListener = null;
    super.onDetach();
}
}

This shows the basics of a fragment that will register a broadcast receiver automatically as it attaches / detaches from the activity.

If the fragment is not attached, it won't be updated.

To update this fragment, call the static method "notifyStuffHappening"

Upvotes: 0

Anitha Manikandan
Anitha Manikandan

Reputation: 1170

.
.
.
Toolbar mToolbar = (Toolbar) getActivity().findViewById(R.id.toolbar_actionbar);
    final Spinner spinner_nav = (Spinner) mToolbar.findViewById(R.id.spinner_nav);
    spinner_nav.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

/////////////////////////Added////////////
adapter.callWrite();
////////////////////////////////////////
        }
    });     
}

public class CategoriesPagerAdapter extends FragmentStatePagerAdapter {

    CharSequence Titles[];
    int NumbOfTabs;
/////////////////////Added///////////////////
Tab1Class tab1;
Tab2Class tab2;
//////////////////////////////

    public CategoriesPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
        super(fm);
        this.Titles = mTitles;
        this.NumbOfTabs = mNumbOfTabsumb;
    }

    @Override
    public Fragment getItem(int position) {
        if (position == 0) {
            tab1 = new Tab1Class();
            return tab1;
        } else if (position == 1) {
            tab2 = new Tab2Class();
            return tab2;
        } else {
            return null;
        }
    }
////////////////////////////Added////////////////////
public void callWrite(){
    if(tab1 != null)
        tab1.writeText();
    if(tab2 != null)
        tab2.writeText();
}
/////////////
.
.
.

Upvotes: 1

Related Questions