LukeP
LukeP

Reputation: 1605

Fragment interaction listeners in FragmentPagers

I am creating a tabbed application using a FragmentPagerAdapter and android.support.v4.view.ViewPager. In order to follow best practices and separation of concerns I have separated my app into several different fragments. Each of the fragments has an interaction listener that requires an Activity to subscribe to. Since I only have one activity in the entire app do I have to make the parent (tabbed navigation) activity implement all the listeners in the entire app? This seems like it would be bad practice and create one large monolithic Activity class that controls the flow of everything.

I have three fragments inside of another fragment that I use as a home page tab. The home page fragment implements the interfaces of the three sub fragments. The problem is that the home page fragment is not an Activity so the sub fragments throw an exception on onAttach.

What am I missing? How can I implement fragment listeners in a tabbed application without making one large and messy Activity class

Upvotes: 1

Views: 994

Answers (2)

LukeP
LukeP

Reputation: 1605

After researching further with different keywords I found a good answer here: https://stackoverflow.com/a/23144683/2435006

They key was to make an onAttachFragment(Fragment f) method rather than using the onAttach(Activity a) and calling it in the onCreate method.

Here is the example from the answer above:

public void onAttachFragment(Fragment fragment)
{
    try
    {
        mListener = (OnInteractionListener) fragment;

    } catch (ClassCastException e)
    {
          throw new ClassCastException(fragment.toString() + " must implement OnInteractionListener");
    }
 }


 @Override
 public void onCreate(Bundle savedInstanceState)
 {
    Log.i(TAG, "onCreate");
    super.onCreate(savedInstanceState);

    this.mContext = getActivity().getApplicationContext();
    onAttachFragment(getParentFragment());
    ....
 }

Upvotes: 2

The Original Android
The Original Android

Reputation: 6215

I think you need a good sample related to Fragments. Here is a sample with detailed explanations @ ViewPager with FragmentPagerAdapter. The listeners are at onCreateView method at the Fragment. You don't want to set a bunch of listeners in the Activity.

Upvotes: 0

Related Questions