Android DrawerLayout 监听事件简单应用

有的书上或者博客上写的是mDrawerLayout.setDrawerListener,不过Android Studio显示该方法已经被弃用,所以我选择了addDrawerListener。

mDrawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                super.onDrawerSlide(drawerView, slideOffset);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerStateChanged(int newState) {
                super.onDrawerStateChanged(newState);
            }
        });

声明私有变量

private DrawerLayout mDrawerLayout;
private static final String TAG = "StuListActivity";

核心代码

mDrawerLayout.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                super.onDrawerSlide(drawerView, slideOffset);
                /*
                //在里面可以对侧边栏动态设置TextView等的文本内容
                TextView username = (TextView) drawerView.findViewById(R.id.username);
                TextView mail = (TextView) drawerView.findViewById(R.id.mail);
                username.setText(CurrentStudentInfo.getCruStu().getName());
                mail.setText(CurrentStudentInfo.getCruStu().getEmail());
                Log.d(TAG, "onDrawerSlide: username = " + username);
                Log.d(TAG, "onDrawerSlide: mail = " + mail);
                */
                Log.d(TAG, "onDrawerSlide: 侧边栏开始滑动");
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                Log.d(TAG, "onDrawerOpened: 打开侧边栏");
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                Log.d(TAG, "onDrawerClosed: 关闭侧边栏");
            }

            @Override
            public void onDrawerStateChanged(int newState) {
                super.onDrawerStateChanged(newState);
                Log.d(TAG, "onDrawerStateChanged: 侧边栏状态发生改变");

            }
        });

小建议多用Log,少用sout,亲身经历,Log很好用

你可能感兴趣的:(Android)