使用OnContextItemSelected从ListView项中检索文本 [英] Retrieving text from a ListView item with OnContextItemSelected

查看:120
本文介绍了使用OnContextItemSelected从ListView项中检索文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有经典上下文菜单的ListView,其中包含删除和类似选项。由于我要从SharedPreferences对象中删除,因此我需要检索键,它是设置到ListView项中的文本。

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.

我尝试了以下代码:

    @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.

推荐答案

您已经正确投射了 AdapterContextMenuInfo

从那里,您可以获取targetView,然后可以将其再次投射到小部件中。我猜这是一个 TextView 。在该 TextView 上,您可以调用简单的 getText()方法。

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();

这篇关于使用OnContextItemSelected从ListView项中检索文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆