检测导航抽屉内片段的可见性

时间:2016-03-11 09:12:02

标签: android android-fragments android-navigation-drawer

我在SDK中有一个片段,包装器应用程序可能会在导航栏中显示。我想从Fragment本身检测何时该片段对用户可见,以便进行跟踪。有没有办法做到这一点?

1 个答案:

答案 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() {
        // ...
    }
}