Call Method in Fragment from Unrelated Class

Viewed 3218

Tricky question here, but I will try and be clear.

Class A: extends FragmentActivity and has the FragmentManager

Class B: extends Fragment and has the fragment's UI

Class C: Unrelated Class

    public class A extends FragmentActivity{
        Fragment fragment = new FragmentActivity();
    }

    public class B extends Fragment{
        public void methodToBeCalled(){
             //do something
}
    }

    public class C{
        //call B's methodToBeCalled() from here
        //note it is not static
    }

What I want to do is call a method which is located in Class B from Class C. Any ideas how I could go about doing this?

A solution would be a way to run this code from Class C:

B fragment = (B) getFragmentManager().findFragmentById(R.id.b);

This does not work (it compiles, but the if statement is always false):

    if (A.getCurrentFragment() instanceof B) {
        B fragment = (B) A.getCurrentFragment();
        fragment.methodToBeCalled();
    }
3 Answers
Related