抽屉导航栏中的开关

问题描述 投票:1回答:1

我在此将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吗?!

java android navigation-drawer
1个回答
3
投票
最后我找到了答案,我把它放在这里给别人看

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

© www.soinside.com 2019 - 2024. All rights reserved.