Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set title of context menu from the selected Listview item

Tags:

android

How can I set title of the context menu from the selected Listview item? This below is my main activity.

public class OListActivity extends ListActivity {
......
......
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        registerForContextMenu(getListView());
        ......
......
        MatrixCursor cursor;
        cursor = NameManager.getnameList();
        startManagingCursor(cursor);
        String[] from = { "name", "info", "status", BaseColumns._ID };
        int[] to = { R.id.name, R.id.info, R.id.status };
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
                R.layout.row, cursor, from, to);
        setListAdapter(adapter);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("Menu");// TODO Change to name of selected listview item.
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu, menu);
    }
.....
.....

I need to set menu.setHeaderTitle to R.id.name. I'm aware of another similer question but it don't mention about dealing with a complex ListView with multiple textviews.

like image 845
Binoy Babu Avatar asked Feb 25 '12 20:02

Binoy Babu


1 Answers

Use the ContextMenuInfo parameter from the onCreateContextMenu() method:

@Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        AdapterView.AdapterContextMenuInfo info;
        try {
            // Casts the incoming data object into the type for AdapterView objects.
            info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        } catch (ClassCastException e) {
            // If the menu object can't be cast, logs an error.
            Log.e(TAG, "bad menuInfo", e);
            return;
        }
        Cursor cursor = (Cursor) getListAdapter().getItem(info.position);
        if (cursor == null) {
            // For some reason the requested item isn't available, do nothing
            return;
        }

        // if your column name is "name"
        menu.setHeaderTitle(cursor.getString(cursor.getColumnIndex("name")));
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu, menu);
    }
like image 186
user Avatar answered Nov 12 '22 04:11

user