Android UI How to - Add menu to ListView








The following code shows how to Add menu to ListView.

Example

Menu xml file

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item
    android:id="@+id/menu_delete"
    android:icon="@android:drawable/ic_menu_delete"
    android:title="Delete Item"
  />
  <item
    android:id="@+id/menu_edit"
    android:icon="@android:drawable/ic_menu_edit"
    android:title="Edit Item"
  />
</menu>

Main activity Java code

package com.java2s.myapplication3.app;
//from   w ww. j a v  a2s .co  m
import android.app.Activity;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity implements AbsListView.MultiChoiceModeListener {

    private static final String[] ITEMS =
            {"XML", "CSS", "HTML", "Java", "Javascript", "SQL"};

    private ListView mList;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mList = new ListView(this);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_activated_1, ITEMS);
        mList.setAdapter(adapter);
        mList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
        mList.setMultiChoiceModeListener(this);

        setContentView(mList);
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        //You can do extra work here update the menu if the
        // ActionMode is ever invalidated
        return true;
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) {
        //This is called when the action mode has ben exited
    }

    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        MenuInflater inflater = mode.getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        SparseBooleanArray items = mList.getCheckedItemPositions();
        switch(item.getItemId()) {
            case R.id.menu_delete:
                //Perform delete actions
                break;
            case R.id.menu_edit:
                //Perform edit actions
                break;
            default:
                return false;
        }
        return true;
    }

    @Override
    public void onItemCheckedStateChanged(ActionMode mode, int position,
                                          long id, boolean checked) {
        int count = mList.getCheckedItemCount();
        mode.setTitle(String.format("%d Selected", count));
    }
}
null