Raphael
Raphael

Reputation: 21

Check if fragment displayed as dialog to change click listener behavior

I am creating an app in which the user should be able add people for meetings.

The structure consists of several fragments managed in the same activity (list_people, person_detail, create_meeting).

I would like to reuse the fragment showing the list of people as a dialog in the create_meeting fragment. And add a person to a meeting by clicking on the person item.

When the list_people fragment is embedded in the view, a click on a person item replace the list_people fragment with a person_detail fragment. This behavior is already implemented with an interface for the main activity.

I am looking for a solution to change the behavior of the click listener whether the list_people fragment is displayed as an embedded fragment or as a dialog. Any ideas of how I could do that?

Any help would be greatly appreciated.Thanks.

Upvotes: 1

Views: 262

Answers (1)

Raphael
Raphael

Reputation: 21

Ok I have found a solution. It is to use a constructor (newInstance) for the fragment in which you can pass variables.

public class ListPeopleFragment extends Fragment {

public static ListPeopleFragment newInstance(boolean nested){
    ListPeopleFragment f = new ListPeopleFragment();

    Bundle args = new Bundle();
    args.putBoolean("nested", nested);
    f.setArguments(args);

    return f;
}

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

    boolean nested = false;
    Bundle arguments = getArguments();
    if (arguments != null)
    {
        nested = getArguments().getBoolean("nested");
    } 

    displayListViewPeople(view, nested);

    return view;
}
}

The displayListViewPeople set the click listener depending on the value of nested.

You instantiate the fragment this way:

ListPeopleFragment nestedFrag = ListPeopleFragment.newInstance(true);

Upvotes: 1

Related Questions