DrawerLayout在方向改变时失去状态

时间:2016-10-24 22:12:32

标签: android navigation-drawer android-orientation drawerlayout android-navigation-drawer

我从按钮的onClick切换DrawerLayout的状态,并禁用其滑动。 这工作正常,但当活动改变其方向时,抽屉不会保持其状态; 如果已打开,则会关闭。它甚至会添加if (!$CLEAN_Var) { return $CLEAN_Var = null; } // validate input $valid = true; // insert data if ($valid) { $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO Table (" ."ColumnNames" .")" ."VALUES(" ."?" .")"; $q = $pdo->prepare($sql); $q->execute(array($CLEAN_Var)); // Once INSERT is completed, we will redirect. header("Location:" 'link.php'); exit; }

我的活动中的代码:

android:configChanges="keyboardHidden|orientation"

一个可能的解决方案是我在活动private DrawerLayout drawer; private int drawerLayoutGravity = Gravity.RIGHT; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); drawer = (DrawerLayout) findViewById(R.id.drawer_layout); disableDrawer(); View btnOpenDrawer = findViewById(R.id.btn_open_drawer); btnOpenDrawer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { toggleDrawerState(); } }); } private void toggleDrawerState() { if (drawer.isDrawerOpen(drawerLayoutGravity)) { drawer.closeDrawer(drawerLayoutGravity); } else { drawer.openDrawer(drawerLayoutGravity); } } /** * doesn't let the user swipe to open the drawer */ private void disableDrawer() { drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); } 上打开DrawerLayout,但我需要在配置更改时避免显示DrawerLayout重新打开。

1 个答案:

答案 0 :(得分:3)

您在抽屉上设置了关闭锁定模式以禁用滑动。即使您已禁用Activity重新创建,方向更改也会触发View上的布局事件,而DrawerLayout会根据锁定设置抽屉状态自我解决的模式。

每当您以编程方式打开/关闭抽屉时,都需要更新锁定模式。

private void toggleDrawerState() {
    if (drawer.isDrawerOpen(drawerLayoutGravity)) {
        drawer.closeDrawer(drawerLayoutGravity);
        drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    } else {
        drawer.openDrawer(drawerLayoutGravity);
        drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN);
    }
}