在抽屉导航栏中切换

Switch in Drawer Navigation bar

我把开关放在抽屉导航栏的菜单项中:

但是当我尝试使用此代码在 activity Oncreate 中访问 Switch 时

        NavigationView  navigationView = findViewById(R.id.nav_view);

    try {

        ((Switch) navigationView.getMenu().findItem(R.id.nav_isactive).getActionView()).setChecked(true);
    }
    catch (Exception ex)
    {
        Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
    }

我遇到了转换错误:

java.lang.ClassCastException: androidx.appcompat.view.menu.MenuItemImpl cannot be cast to android.widget.Switch

和 ex.getMessage() 告诉我:不能将 linearLayout 投射到 Switch?!!

我终于找到了答案,我把它放在这里供其他人使用

    NavigationView  navigationView = findViewById(R.id.nav_view);


MenuItem menuItem = navigationView.getMenu().findItem(R.id.nav_isactive); // This is the menu item that contains your switch
Switch drawer_switch = (Switch) menuItem.getActionView().findViewById(R.id.m_swisactive);
drawer_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // Your logic goes here
        Toast.makeText(MainActivity.this, String.valueOf(isChecked), Toast.LENGTH_SHORT).show();
    }
});