【问题标题】:How to get the item id in an onItemClick handler如何在 onItemClick 处理程序中获取项目 ID
【发布时间】:2011-04-05 14:06:14
【问题描述】:

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

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?

【问题讨论】:

  • long类型的id参数不是对你有帮助吗??
  • 获取选中项目的内容,使用 Object o=lv.getItemAtPosition(position);对象 o 可以进一步用于获取项目。
  • setListAdapter 是做什么的,为什么会出现在 list = getListView() 之前?

标签: android onclick onclicklistener simpleadapter


【解决方案1】:

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

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

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

【讨论】:

  • adapterView 通常不是适配器。这是一个使用适配器的视图,因此具有方法getAdapter()。因此,在您的示例中,您应该改为调用 adapterView.getAdapter()
  • 是否适用于SimpleAdapter
【解决方案2】:

谢谢 Zack,我可以用你的帖子解决...太好了!!! ... 我将一个活动的参数发送到另一个活动:

Intent myIntent = new Intent(Clientes.this, Edc.class);
Cursor cursor = (Cursor) adapter.getItem(position);
myIntent.putExtra("CLIENTE_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(myIntent);

在其他活动(EDC)中......我得到了参数:

int _clienteId = getIntent().getIntExtra("CLIENTE_ID", 0);

【讨论】:

    【解决方案3】:

    onItemclick 怎么样:

    categoryCursor.moveToPosition(position);
    

    然后从返回的光标中获取助手的 ID?

    【讨论】:

      【解决方案4】:

      使用SimpleCursorAdapteronItemClick 函数传入所选项目的数据库ID。所以,解决方案很简单

      long category_id = id
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多