如何找到包含特定视图的片段?
很容易找到知道片段和视图ID的视图:
fragment.getView().findViewById(R.id.foo)
但我想做的是逆转:了解视图,找到片段。
答案 0 :(得分:0)
到目前为止,最好的想法是:
予。将根视图的标记设置为膨胀它的片段:
// 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。然后,在视图的父母之间找到根视图相对容易:
// 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。用法:
Fragment f = getTagFragment(view);
PS我甚至可以place an onClick handler into a Fragment,它确实有效!