Retrieving text from a ListView item with OnContextItemSelected

流过昼夜 提交于 2019-12-10 19:56:36

问题


I've a ListView with a 'classic' context menu with delete and similar options. Since I'm deleting from a SharedPreferences object, I need to retrieve the key, which is the text set into ListView's items.

I've tried the following code:

    @Override
    public boolean onContextItemSelected(MenuItem item){
        AdapterContextMenuInfo saved = (AdapterContextMenuInfo) item.getMenuInfo();

        TextView view = (TextView)findViewById((int) saved.id);

        Log.d("DEBUG:", "before key");
        String key = view.getText().toString();
        Log.d("DEBUG:", "after...");

        switch (item.getItemId()){
            case R.id.conmenu_delete:
                return true;

            case R.id.conmenu_copy:
                return true;

            case R.id.conmenu_send:
                return true;

            default:
                return super.onContextItemSelected(item);
        }
    }

But, unfortunately, it crashes while trying to retrieve the text from the View, as I know from logs.


回答1:


You have already correctly casted the AdapterContextMenuInfo.
From there, you can get the targetView which you can cast again into the widget. I guess it's a TextView in your case. On that TextView you can call the simple getText() method.

@Override
public boolean onContextItemSelected(MenuItem item) {

           AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
           String key = ((TextView) info.targetView).getText().toString();

           switch (item.getItemId()){
                case R.id.conmenu_delete:
                    return true;

                case R.id.conmenu_copy:
                    return true;

                case R.id.conmenu_send:
                    return true;

                default:
                    return super.onContextItemSelected(item);
          }
}

If your list is populated with custom objects, you obviously have to cast it to the respective type, for example:

Person person = (Person) getListAdapter().getItem(info.position);
String key = person.getName();



回答2:


 @Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

    Object obj = getListView().getItemAtPosition(info.position);
    String title = obj.toString();



}


来源:https://stackoverflow.com/questions/14328596/retrieving-text-from-a-listview-item-with-oncontextitemselected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!