Question: So basically I want to dynamically add items to a menu and each item should have a switch. I can do that with the code

So basically I want to dynamically add items to a menu and each item should have a switch. I can do that with the code below, however I want it to work as the page is being created rather than when an item is clicked. I've tried moving the for loop in bold below out of the onClickListener function but that doesn't seem to work. I am using Android Studio 
for(int i = 0; i < listView.getAdapter().getCount(); i++){ NavigationView navigationView = findViewById(R.id.nav_view); Menu menu = navigationView.getMenu(); menu.add(parameterList.get(i).getLabel()); }
 --------------------------------------------------------------------------------------- @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.activity_main);
adapter = new ArrayAdapter<>(ViewPagerFragmentActivity.this, android.R.layout.simple_list_item_activated_1, optionsArray);
 listView = (ListView) findViewById(android.R.id.list); listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); //When an item is selected it will display the chosen items at the bottom of the screen listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView parent, View view, int position, long id) { //String selectedItem = (String)(parent.getItemAtPosition(position)); //Log.v(TAG, selectedItem); SparseBooleanArray checked = listView.getCheckedItemPositions(); ArrayList selectedArray = new ArrayList<>(); for(int i = 0; i < listView.getAdapter().getCount(); i++){ NavigationView navigationView = findViewById(R.id.nav_view); Menu menu = navigationView.getMenu(); menu.add(2,1,1,parameterList.get(i).getLabel()).setActionView(R.layout.switch_item); if(checked.get(i)){ selectedArray.add(parameterList.get(i).getLabel()); } } } }); //Connect to the sensor and load the metrics ViewPagerFragmentActivity.Load load = new ViewPagerFragmentActivity.Load(); load.execute(); }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!