HappyPoofySquirrel HappyPoofySquirrel - 1 year ago 145
Android Question

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

Answer Source

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

Switch mySwitch = new Switch(this);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download