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.
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.
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!