我在SDK中有一个片段,包装器应用程序可能会在导航栏中显示。我想从Fragment本身检测何时该片段对用户可见,以便进行跟踪。有没有办法做到这一点?
答案 0 :(得分:1)
public class MyFragment extends Fragment {
private DrawerLayout mDrawerLayout;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_fragment, container, false);
// walk up the view tree and look for the DrawerLayout
for (ViewParent parent = container.getParent(); parent != null; parent = parent.getParent()) {
if (parent instanceof DrawerLayout) {
mDrawerLayout = (DrawerLayout) parent;
mDrawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
@Override
public void onDrawerOpened(View drawerView) {
onShown();
}
@Override
public void onDrawerClosed(View drawerView) {
onHidden();
}
});
break;
}
}
return view;
}
@Override
public void onDestroyView() {
if (mDrawerLayout != null) {
mDrawerLayout.setDrawerListener(null);
}
super.onDestroyView();
}
private void onShown() {
// ...
}
private void onHidden() {
// ...
}
}