Android toolbar item OnClickListener

I have a toolbar and an (add) item that, when clicked, adds a view to the listView below. However, onOptionsItemSelected

it gives a one click effect, so it only adds one view, and in my case I need multiple views, so it takes multiple clicks. How to set everything up so that the element works like onClickListener

, and not one click?

public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id =={
        final TextView noProject = (TextView) findViewById(;

        final ArrayList<String> listItems=new ArrayList<String>();
        final ListAdapter addAdapter = new ArrayAdapter<String>(this,
                    R.layout.list_item,, listItems);
        final ListView lv = (ListView) findViewById(;

        listItems.add("New Project");
        ((ArrayAdapter) addAdapter).notifyDataSetChanged();

    if (id == {
        return true;

    return super.onOptionsItemSelected(item);



source to share

1 answer

Android always listens for clicks on menu items. And when clicked, your action will take place, so you will need to click multiple times anyway if you want to add this function to the menu.

I usually set up my list adapter in onCreate or onCreateView. After creating it, you can do addAdapter.clear () and addAdapter.add (item). You don't need to reference your lists right away as the ArrayAdapter.add () method is set up to add to that list, and then if I'm not mistaken, you can get rid of notifyDataSetChange () - I've never had to use this method with with any of the default list adapters or with custom adapters I wrote..clear (),. add (),. insert () and .remove () should suffice.

My list is usually filled with a for loop. If you want to add multiple views, could you just set up a loop instead of waiting or requiring more clicks?

I may not fully understand what usecase is, but basic for loop seems to be the answer here.


//For Each Loop - "For each individualItem in itemHolder"
for(ItemType individualItem : itemHolder){


or you can do the traditional for loop

//"For i(index) starting at index 0, run until index < itemHolder.getItemCount() is false"
//for(initialize index variable : condition check : increment after each     iteration)
for(int index =0; index<itemHolder.getItemCount(); index++)


Something like that. I have compiled the method names, obviously they will depend on your data structures.



All Articles