DrawerLayout onDrawerClosed()调用两次

时间:2017-10-26 05:28:06

标签: java android listener android-view drawerlayout

我使用菜单抽屉作为核对表和onDrawerClosed,取决于int值将向用户收费或不保存更改。但是,onDrawerClosed方法调用两次,一次使用int和正确的值,一次使用int,值为0?这导致我的程序调用if和else语句,以便保存更改并提示他们付款。

//Used so that when drawer closed banned list saves
public void drawerListener(){
    mDrawer.addDrawerListener(new DrawerLayout.DrawerListener() {
        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
        }

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

        @Override
        public void onDrawerClosed(View drawerView) {
            System.out.println("Cost of Changes:" + customAdaptor.getUserCostOfChange());
            if (customAdaptor.getUserCostOfChange() > 0) {
                getBuyAlert(customAdaptor.getUserCostOfChange());
                customAdaptor.setUserCostOfChange(0);
            }
            else {
                bannedList = customAdaptor.getBannedList();
                databaseReference.child("BannedApps").setValue(bannedList);
            }
        }

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


Output:
10-26 01:30:40.346 23822-23822/com.shuffle.v01 I/System.out: Cost of 
Changes:1000

10-26 01:30:40.450 23822-23822/com.shuffle.v01 I/System.out: Cost of 
Changes:0

1 个答案:

答案 0 :(得分:2)

确保您恰好拨打addDrawerListener()一次,因为“添加”是一个听众,不是“设置”。

话虽如此,请确保从onCreate()活动(或Fragment的类似回调)调用该代码。否则,如果你从onStart()onResume()执行它,那么每次调用这些回调时你都会添加一个新的监听器。