Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have made a simple app that just brings up an AlertDialog, with four items in the list. I register a context menu. When I long click one of the items, I get the context menu. I then select an item from the context menu, but onContextItemSelected never gets called. Any help? Thanks.

test.java:

package com.cerulean.tech.creations.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

public class test extends Activity {

    private String[] files;
    AlertDialog alert;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        files = new String[4];
    }

    public void selectScheme(View v) {
        files[0] = "<New Scheme>";
        files[1] = "test1";
        files[2] = "test2";
        files[3] = "test3";
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setItems(files, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int item) {
                   }});  
        alert = builder.create();
        alert.show();
        registerForContextMenu(alert.getListView());
    }


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("Context Menu");
        menu.add(0, v.getId(), 0, "Delete");
        menu.add(0, v.getId(), 0, "Cancel");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        return false;
    }
}

In main.xml, I just a button defined with android:onClick="selectScheme"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

After this line:

    registerForContextMenu(alert.getListView());

type this:

    alert.getListView().setOnCreateContextMenuListener(this);

And instead of onContextItemSelected(MenuItem item) function use this:

@Override
public boolean onMenuItemSelected(int featureId, MenuItem menuItem) {

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...