检测哪个所选项目(在 ListView 中)产生了 ContextMenu (Android)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2321332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:24:40  来源:igfitidea点击:

Detecting which selected item (in a ListView) spawned the ContextMenu (Android)

androidlistviewcontextmenu

提问by Jeremy Logan

I have a ListViewthat will allow the user to long-press an item to get a context menu. The problem I'm having is in determining which ListItemthey long-pressed. I've tried doing this:

我有一个ListView,它允许用户长按一个项目来获取上下文菜单。我遇到的问题是确定ListItem他们长按了哪些。我试过这样做:

myListView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
  @Override public void onCreateContextMenu(ContextMenu menu, final View v, ContextMenuInfo menuInfo) {
   menu.add("Make Toast")
    .setOnMenuItemClickListener(new OnMenuItemClickListener() {
     @Override public boolean onMenuItemClick(MenuItem item) {
      String toastText = "You clicked position " + ((ListView)v).getSelectedItemPosition();
      Toast.makeText(DisplayScheduleActivity.this, toastText, Toast.LENGTH_SHORT).show();
      return true;
     }
    });
  } 
 });

but it just hangs until an ANRpops up. I suspect that after the menu is created the ListItemis no longer selected.

但它只是挂起,直到ANR弹出。我怀疑在创建菜单后ListItem不再选择。

It looks like you could monitor for clicks or long-clicks then record the clicked item there:

看起来您可以监视点击或长按,然后在那里记录点击的项目:

 mArrivalsList.setOnItemLongClickListener(new OnItemLongClickListener() {
  @Override public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
   // record position/id/whatever here
   return false;
  }
 });

but that feels majorly kludgey to me. Does anyone have any better solutions for this?

但这对我来说感觉很笨拙。有没有人对此有更好的解决方案?

回答by Eric Burke

I do exactly this. In my onCreateContextMenu(...)method, I cast the ContextMenu.ContextMenuInfoto AdapterView.AdapterContextMenuInfo. From there, you can get the targetView, which you cast again to the widget. The complete code is available in HomeActivity.java, look for the onCreateContextMenu(...)method.

我正是这样做的。在我的onCreateContextMenu(...)方法,我投了ContextMenu.ContextMenuInfoAdapterView.AdapterContextMenuInfo。从那里,您可以获得 targetView,您再次将其投射到小部件。完整代码在HomeActivity.java 中,查找onCreateContextMenu(...)方法。

@Override
public void onCreateContextMenu(ContextMenu contextMenu,
                                View v,
                                ContextMenu.ContextMenuInfo menuInfo) {
    AdapterView.AdapterContextMenuInfo info =
            (AdapterView.AdapterContextMenuInfo) menuInfo;
    selectedWord = ((TextView) info.targetView).getText().toString();
    selectedWordId = info.id;

    contextMenu.setHeaderTitle(selectedWord);
    contextMenu.add(0, CONTEXT_MENU_EDIT_ITEM, 0, R.string.edit);
    contextMenu.add(0, CONTEXT_MENU_DELETE_ITEM, 1, R.string.delete);
}

Note that I store the selected text as well as the select id in private fields. Since the UI is thread confined, I know the selectedWord and selectedWordId fields will be correct for later actions.

请注意,我将所选文本以及选择 ID 存储在私有字段中。由于 UI 是线程限制的,我知道 selectedWord 和 selectedWordId 字段对于以后的操作是正确的。

回答by Dan Lew

First of all, I'm wondering if you're making things a little overly complicated by using View.setOnCreateContextMenuListener(). Things get a lot easier if you use Activity.registerForContextMenu(), because then you can just use Activity.onCreateContextMenu()and Activity.onContextItemSelected()to handle all of your menu events. It basically means you don't have to define all these anonymous inner classes to handle every event; you just need to override a few Activity methods to handle these context menu events.

首先,我想知道您是否通过使用View.setOnCreateContextMenuListener(). 如果您使用Activity.registerForContextMenu(),事情会变得容易得多,因为这样您就可以使用Activity.onCreateContextMenu()Activity.onContextItemSelected()处理所有菜单事件。这基本上意味着您不必定义所有这些匿名内部类来处理每个事件;您只需要覆盖一些 Activity 方法来处理这些上下文菜单事件。

Second, there's definitely easier ways to retrieve the currently selected item. All you need to do is keep a reference either to the ListViewor to the Adapterused to populate it. You can use the ContextMenuInfo as an AdapterContextMenuInfo to get the position of the item; and then you can either use ListView.getItemAtPosition()or Adapter.getItem()to retrieve the Objectspecifically linked to what was clicked. For example, supposing I'm using Activity.onCreateContextMenu(), I could do this:

其次,肯定有更简单的方法来检索当前选定的项目。您需要做的就是保留ListViewAdapter用于填充它的或的引用。您可以使用 ContextMenuInfo 作为 AdapterContextMenuInfo 来获取项目的位置;然后您可以使用ListView.getItemAtPosition()Adapter.getItem()检索Object特定链接到点击的内容。例如,假设我正在使用Activity.onCreateContextMenu(),我可以这样做:

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    // Get the info on which item was selected
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;

    // Get the Adapter behind your ListView (this assumes you're using
    // a ListActivity; if you're not, you'll have to store the Adapter yourself
    // in some way that can be accessed here.)
    Adapter adapter = getListAdapter();

    // Retrieve the item that was clicked on
    Object item = adapter.getItem(info.position);
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    // Here's how you can get the correct item in onContextItemSelected()
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    Object item = getListAdapter().getItem(info.position);
}

回答by Ali Ashraf

this is another way on how to create context menu n how to delete the item selected here is the whole code

这是关于如何创建上下文菜单的另一种方法如何删除此处选择的项目是整个代码

     public class SimpleJokeList extends Activity {
public static final int Upload = Menu.FIRST + 1;
public static final int Delete = Menu.FIRST + 2;
int position;
ListView lv;
EditText jokeBox;
Button addJoke;
MyAdapter adapter;
private ArrayAdapter<String> mAdapter;
private ArrayList<String> mStrings = new ArrayList<String>();
String jokesToBeAdded;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.simplejokeui);



    lv=(ListView)findViewById(R.id.jokelist);
    addJoke=(Button)findViewById(R.id.addjoke);
    jokeBox=(EditText)findViewById(R.id.jokebox);


    mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mStrings);


    registerForContextMenu(lv);
    listItemClicked();
    addJokes();

private void addJokes() {
    // TODO Auto-generated method stub
    addJoke.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            jokesToBeAdded=jokeBox.getText().toString();
            if(jokesToBeAdded.equals("")){
            Toast.makeText(getApplicationContext(), "please enter some joke", Toast.LENGTH_LONG).show();
            }
            else{
                lv.setAdapter(mAdapter);
                mAdapter.add(jokesToBeAdded);
                jokeBox.setText(null);
            }   
        }
    });
}
private void listItemClicked() {
    // TODO Auto-generated method stub
    lv.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {
            // TODO Auto-generated method stub
            position=arg2;
            return false;
        }
    });
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    // TODO Auto-generated method stub
    super.onCreateContextMenu(menu, v, menuInfo);
    populateMenu(menu);
    menu.setHeaderTitle("Select what you wanna do");

}
private void populateMenu(ContextMenu menu) {
    // TODO Auto-generated method stub
     menu.add(Menu.NONE, Upload, Menu.NONE, "UPLOAD");
        menu.add(Menu.NONE, Delete, Menu.NONE, "DELETE");
}
 @Override
    public boolean onContextItemSelected(MenuItem item) 
    {
     return (applyMenuChoice(item) || super.onContextItemSelected(item));
    }


private boolean applyMenuChoice(MenuItem item) {
    // TODO Auto-generated method stub
    switch (item.getItemId()) 
    {   
         case Delete:

             String s=mAdapter.getItem(position);
             mAdapter.remove(s);
            // position--;
             Toast.makeText(getApplicationContext(),"Congrats u HAve Deleted IT", Toast.LENGTH_LONG).show();
        return (true);
    }
    return false;
}

回答by sami boussacsou

And don't forget to put this

不要忘记把这个

registerForContextMenu(listview);

in your onCreatemethod to get your context Menu visible.

在您的onCreate方法中使您的上下文菜单可见。

回答by Patrick Kafka

Isn't the view argument the actual selected row's view, or am I missing the question here?

视图参数不是实际选定行的视图,还是我在这里错过了问题?

ListView lv;
private OnItemLongClickListener onLongClick = new OnItemLongClickListener() {
    public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
            int arg2, long arg3) {
        lv.showContextMenuForChild(arg1);
        lv.showContextMenu();
        return false;
    }
};

回答by Nate

We have used with success:

我们成功地使用了:

@Override
public boolean onContextItemSelected
(
MenuItem item
)
    {
    if (!AdapterView.AdapterContextMenuInfo.class.isInstance (item.getMenuInfo ()))
        return false;

    AdapterView.AdapterContextMenuInfo cmi =
        (AdapterView.AdapterContextMenuInfo) item.getMenuInfo ();

    Object o = getListView ().getItemAtPosition (cmi.position);

    return true;
    }

回答by Omid Omidi

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
    View TargetV=(View) info.targetView;
    text1 = (String) ((TextView) TargetV.findViewById(R.id.textView1)).getText();
    text2 = (String) ((TextView) TargetV.findViewById(R.id.textView2)).getText();
    if(List3Ok){
        text3 = (String) ((TextView) TargetV.findViewById(R.id.textView3)).getText();   
    }
    selectedWord = text1 + "\n" + text2 + "\n" + text3;
    selectedWordId = info.id;
    menu.setHeaderTitle(selectedWord);
    MenuInflater inflater = this.getActivity().getMenuInflater();
    inflater.inflate(R.menu.list_menu, menu);
}

回答by Andrey Bulanov

I case you are using SimpleCursorAdapderyou may do it like this

如果你正在使用SimpleCursorAdapder你可以这样做

    @Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    getActivity().getMenuInflater().inflate(R.menu.project_list_item_context, menu);

    // Getting long-pressed item position
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
    int position = info.position;

    // Get all records from adapter 
    Cursor c = ((SimpleCursorAdapter)getListAdapter()).getCursor();                     

    // Go to required position
    c.moveToPosition(position);

    // Read database fields values associated with our long-pressed item
    Log.d(TAG, "Long-pressed-item with position: " + c.getPosition());
    Log.d(TAG, "Long-pressed-item _id: " + c.getString(0));
    Log.d(TAG, "Long-pressed-item Name: " + c.getString(1));
    Log.d(TAG, "Long-pressed-item Date: " + c.getString(2));
    Log.d(TAG, "Long-pressed-item Path: " + c.getString(3));

    // Do whatever you need here with received values

}