Touching on the question here, I want to know the feasibility of creating resource ids for dynamically created popup menu items.
A little background: my popup menu contains a "create new file" item in addition to an item for every file found in a given directory. The problem; since I don't know how many files exist in the directory when the app is started, I can't hard code these menu items in my xml file, hence they have no resource ids. I need to assign resource ids for the items in my popup menu so I can create a View variable from an individual item's resource id, i.e:
View menuItemView = getActivity().getWindow().getDecorView().findViewById(R.id.item_id);
I see that one overloaded version of getMenu().add() accepts itemID as a parameter. Can I set this parameter with an int during runtime and then later reference it as a resource id for my purpose above?
This is my complete popup menu code, showcasing the way I dynamically generate menu items:
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.new_track:
trackSelectButton.setText("...");
Toast.makeText(getActivity(), "Name your new track.", Toast.LENGTH_SHORT).show();
txtTrackName.setVisibility(txtTrackName.VISIBLE);
return true;
default:
selectedTrackName = (item.getTitle().toString());
trackSelectButton.setText(selectedTrackName);
for (int i = 0; i < trackListing.length; i++) { //add a menu item for each existing track
if (trackListing[i].getName().equals(selectedTrackName)) {
selectedTrack = trackListing[i];
AudioRecorder.setFile(selectedTrack);
}
}
return true;
}
}
});
MenuInflater popupInflater = popup.getMenuInflater();
popupInflater.inflate(R.menu.popup_menu_track_selection, popup.getMenu());
popup.show();
How can I dynamically generate resource ids for popup menu items? (aka assigning resource ids without an xml file)