Answered step by step
Verified Expert Solution
Question
1 Approved Answer
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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started