简体   繁体   中英

Switch in Drawer Navigation bar

I put Switch in menu item of Drawer navigation bar with this : 在此处输入图片说明

在此处输入图片说明

but when i try to access Switch in activity Oncreate with this code

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

i Got cast error :

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

and on ex.getMessage() tell me : Cant not cast linearLayout to Switch?!!

finaly i find answer and i put it here for others

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM