onListItemClick 中的 getTag() 始终为 null

发布于 2025-01-07 04:35:53 字数 866 浏览 0 评论 0原文

我有一个 ListView,我用一个 CursorAdapter 填充它,如下所示:

SimpleCursorAdapter.ViewBinder viewBinder = new SimpleCursorAdapter.ViewBinder() {
    public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
        if(columnIndex == cursor.getColumnIndex(MyTableColumns._ID))
        {
            view.setTag(cursor.getInt(columnIndex));
        }
        // some other stuff
    }
};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.my_item_renderer, cursor, from, to);
adapter.setViewBinder(viewBinder);

目的是从单击的列表项中获取 ID:

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    Object obj = v.getTag();
    int myId = Integer.parseInt(obj.toString());
}

但是,这始终返回 。我在忽略什么?现在我只是使用隐藏的文本字段,但我想知道我做错了什么。

I have a ListView that I'm populating with a CursorAdapter like this:

SimpleCursorAdapter.ViewBinder viewBinder = new SimpleCursorAdapter.ViewBinder() {
    public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
        if(columnIndex == cursor.getColumnIndex(MyTableColumns._ID))
        {
            view.setTag(cursor.getInt(columnIndex));
        }
        // some other stuff
    }
};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.my_item_renderer, cursor, from, to);
adapter.setViewBinder(viewBinder);

The aim is to get the ID from the list item clicked:

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    Object obj = v.getTag();
    int myId = Integer.parseInt(obj.toString());
}

However this is always returning null. What am I overlooking? For now I'm just using a hidden text field but I'd like to know what I was doing wrong.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一口甜 2025-01-14 04:35:53

onListItemClick() 为您提供一个视图,即列表中的行。 ViewBinder 将值绑定到该行内的 TextView。因此,您调用 setTag() 的视图与您调用 getTag() 的视图不同。

您可以扩展 SimpleCursorAdapter,以便可以在正确的视图上调用 setTag(),也可以在 onListItemClick() 中获取 v 的第一个子视图code> 并获取其标签。

onListItemClick() provides you with a view that is the row in the list. ViewBinder binds values to the TextViews inside this row. Thus the view you call setTag() on is not the same as the view you call getTag() on.

You can either extend SimpleCursorAdapter so you can call setTag() on the correct view, or you can get the first child view of v in onListItemClick() and get the tag of that.

烟酉 2025-01-14 04:35:53

您在设置标签时尝试过这个吗?

view.setTag(new Integer(cursor.getInt(columnIndex)));

Have you tried this when setting your tag?

view.setTag(new Integer(cursor.getInt(columnIndex)));
人间不值得 2025-01-14 04:35:53

也许您的“if”语句只是返回 false,因此没有设置任何 Tag 值?

Maybe your "if" statement simply returns false and thus no Tag value gets set?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文