0

How do I find the fragment that includes a particular view?

It is easy to find a view knowing the fragment and the view id:

fragment.getView().findViewById(R.id.foo)

But what I want to do is the reversal: knowing the view, find the fragment.

18446744073709551615
  • 16,368
  • 4
  • 94
  • 127
  • loop in your fragments list and check if "fragment.getView().findViewById(R.id.foo) != null " – Rami Nov 12 '14 at 11:52

1 Answers1

0

So far the best idea is:

I. Set the root view's tag to the fragment that inflated it:

// in a class that extends Fragment:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_id, container, false);

    rootView.setTag(this); // <======= !!!

    return rootView;
}

II. Then, it's relatively easy to find that root view among view's parents:

// in some utility class:
public static Fragment getTagFragment(View view) {
    for (View v = view; v != null; v = (v.getParent() instanceof View) ? (View)v.getParent() : null) {
        Object tag = v.getTag();
        if (tag != null && tag instanceof Fragment) {
            return (Fragment)tag;
        }
    }
    return null;
}

III. Usage:

    Fragment f = getTagFragment(view);

PS I can even place an onClick handler into a Fragment, and it works!

Community
  • 1
  • 1
18446744073709551615
  • 16,368
  • 4
  • 94
  • 127