getParentFragment API 16

android, android-fragments

Solution

Based on your comment if you want to talk back from the "items" in your `ViewPager` (I'm guessing this is a `Fragment`) to the container of the `ViewPager` which is a `FragmentActivity` you can use an interface.

(1) Either declar the interface in the `Fragment` itself or as a separate file (2) "Initialize" the inteface in your fragment's onAttach method. For example

 private SomeInterface blah;

 @Override
 public void onAttach(Activity activity){
    blah = (SomeInterface) activity;
 }

(3) Implement the interface in your `FragmentActivity`.

You can then callback to the `FragmentActivity` from your `Fragment`. From there you can call any method you want within the `FragmentActivity` or, if you get a reference to any of the other fragments that are loaded into your `ViewPager`, call any public method within that `Fragment`. This allows you to communicate between fragments and their container without a memory leak.

Problem

We all know `getParentFragment` of `Fragment` is introduced in API 17. So what if we want to get parent fragment in API 16 and below (Considering that I use native `Fragment` with support `FragmentStatePagerAdapter` and have no problem with nested fragments) Is there any better way than mine? In parent: ``` public class ParentFragment extends Fragment { public static ParentFragment StaticThis; ... @Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { super.onCreate(savedInstanceState); StaticThis = this; ... } ``` In child: ``` if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) parentFragment = (ParentFragment) getParentFragment(); else parentFragment = ParentFragment.StaticThis; ```

Original source