HappyPoofySquirrel
HappyPoofySquirrel

Reputation: 109

On Check Changed Listener For Menu Item Switch

I have a navigation drawer that contains an undetermined number of switchable items. The Nav items are added from a list of objects using a forloop. The object contains a string for the title, and a boolean to set the switch as enabled or disabled. They have to be switches no checkboxes etc...

My issues is setting an onCheckChangedListener for each item.

My Code

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

 ArrayList<MyObject> myList; 

 for(int i = 0; i > myList.size()-1; i++){    

            MyObject item = myList.get(i);    

            String name = item.getName();    

            Boolean isDisabled = item.getDisabled();    

            navigationView.getMenu().add(name).setActionView(new Switch(this)).setChecked(isDisabled);    
}    

How do i then set a listener on an individual switch?*

 mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // do something, 
            }
          });

I have tried //i get ClassCastException

   Switch mySwitch = (Switch) navigationView.getMenu().add(name).setActionView(new Switch(this)).setChecked(isDisabled);

Any help would be much apreciated. Thank you

Upvotes: 0

Views: 704

Answers (1)

Greg Ennis
Greg Ennis

Reputation: 15379

You should be able to populate your menu in this way:

Switch mySwitch = new Switch(this);
mySwitch.setOnCheckedChangeListener(...);
navigationView.getMenu().add(name).setActionView(mySwitch).setChecked(isDisabled);    

Upvotes: 1

Related Questions