如何在 onItemClick 处理程序中获取项目 ID [英] How to get the item id in an onItemClick handler

查看:17
本文介绍了如何在 onItemClick 处理程序中获取项目 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两列 category_idname 的类别表.我创建了一个名为 CategoryDataHelper 的数据助手类.我有一个名为 getCategoryCursor() 的方法,该方法从类别表中获取 id 和名称并返回光标.使用该光标,我使用 SimpleCursorAdapter 来显示类别列表.它工作正常.

I have a category table with two columns category_id and name. I have created a data helper class named CategoryDataHelper. I have a method named getCategoryCursor() of that helper class which fetches the id and the name from the category table and returns the cursor. Using that cursor, I have used SimpleCursorAdapter to display the list of categories. It is working fine.

public class Categories extends ListActivity  {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        categoryDataHelper = new CategoryDataHelper(getApplicationContext());
        Cursor categoryCursor  = categoryDataHelper.getCategoryCursor();
        ListAdapter adapter = new SimpleCursorAdapter (
                this,  
                android.R.layout.simple_list_item_1,
                categoryCursor,                                              
                new String[] { CategoryDataHelper.NAME },           
                new int[] {android.R.id.text1});  

        // Bind to our new adapter.
        setListAdapter(adapter);

        list = getListView();
        list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // Here I want the category_id  
            }
        });
    }    
}

现在我想实现一个 OnItemClickListener 并发送一个带有所选类别的 category_id 的 Intent.如何在 onItemClick() 方法中获取 id?

Now I want to implement an OnItemClickListener and send an Intent with the category_id of the selected category. How can I get the id in the onItemClick() method?

推荐答案

您可能应该从适配器获取光标.这样,如果您的光标被替换,您仍然可以获得有效的光标.

You probably should get the cursor from the adapter. This way if your cursor gets replaced you are still are still getting a valid cursor.

Cursor cursor = ((SimpleCursorAdapter) adapterView).getCursor();
cursor.moveToPosition(position);
long categoryId = cursor.getLong(cursor.getColumnIndex(CategoryDataHelper.ID));

或使用 "category_id" 或您的列名称代替 CategoryDataHelper.ID.

or use "category_id" or whatever the name of your column is in place of CategoryDataHelper.ID.

这篇关于如何在 onItemClick 处理程序中获取项目 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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