在抽屉导航栏中切换

时间:2019-12-23 17:47:34

标签: java android navigation-drawer

我将Switch放置在Drawer导航栏的菜单项中: enter image description here

enter image description here

但是当我尝试使用此代码访问活动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吗?!

1 个答案:

答案 0 :(得分:2)

最后我找到答案,我把它放在这里给其他人

    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();
    }
});