JasonM JasonM - 27 days ago 20
Android Question

mend.findItem explanation and confusion

I'm new to android development and kinda to Java as well.
I'm learning how to add buttons to actionbar - everything is working, but I don't understand few things.

//Showing small icons at actionbar
@Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
menuItem = menu.findItem(R.id.recBin); // Finds the button in Actionbar and gets the ID
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {
case R.id.recBin: // Actions for delete button
dbHandler.remove(getID());
displayTaskList();
menuItem.setVisible(false); // Hide the button
break;
case R.id.editBtn: // Actions for editbutton

Toast.makeText(MainActivity.this,
"EDIT", Toast.LENGTH_LONG).show();

break;
case R.id.closeBtn:

Toast.makeText(MainActivity.this,
"CLOSE", Toast.LENGTH_LONG).show();

break;
default:
break;
}

return true;
}


This line: menuItem = menu.findItem(R.id.recBin); Is for what exactly? I took it off and my app crashed, so I understand that it's mandatory. What I don't understand is what icons ID should I put at bold space? It has to be from "menu" right, but does it matter which id I take? For instance, if I took R.id.closeBtn instead of recBin? As long as it's an id from menu, it works?
P.S. I hope this isn't a terrible question [probably is] and I'm sorry if so.

Solution:
Turns out you can simply get ID's. Stupid and simple.

private MenuItem item1, item2, item3;

//Showing small icons at actionbar
@Override
public boolean onCreateOptionsMenu(Menu menu){

MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);

item1 = menu.findItem(R.id.recBin); // Rec button
item2 = menu.findItem(R.id.editBtn); // Edit button
item3 = menu.findItem(R.id.closeBtn); // Close button

return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.recBin: // Actions for delete button
dbHandler.remove(getID());
displayTaskList();
item1.setVisible(false); item2.setVisible(false); item3.setVisible(false); // Hiding all buttons
break;
case R.id.editBtn: // Actions for editbutton

item1.setVisible(false); item2.setVisible(false); item3.setVisible(false); // Hiding all buttons
break;
case R.id.closeBtn:
item1.setVisible(false); item2.setVisible(false); item3.setVisible(false); // Hiding all buttons
break;
default:
break;
}
return true;
}

Answer

It's a reference to MenuItem, but it would be easier if you do:

case R.id.recBin: // Actions for delete button
        dbHandler.remove(getID());
        displayTaskList();
        item.setVisible(false); // Hide the button
        break;

You can safely remove the reference afterwards

Comments