-2

I'm filling a custom ListView (by custom I mean with a specific layout) with a json request, an i'd like to implement an OnItemClickListener. So i did that :

ListView lv = (ListView) findViewById(R.id.MessageList);
    lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {


        }
    });

My problem is that I want to exploit the selected item of the ListView, but I can only know which item has been selected (the first one, second one, etc), i'd like to associate my Database's ID (the primary key i got with json deserialize) with the ListView ID, or something like that.

Is there any way to do this ?

Best regards.

4

3 回答 3

2

在您的适配器中,覆盖getItemId()以返回您正在使用的 ID:(在此示例中,您的适配器适用于 JSONObjects,并且您的 id 是您的 json 对象中的键“id”长期引用的)

@Override
public long getItemId(int position) {
    return getItem(position).optLong("id");
}

这样,在您的onItemClickListener中,arg3实际是被点击项目的 id。

于 2013-06-14T15:50:46.613 回答
0

确保MyClassWithGettersSetters包含您需要的数据库 ID。

然后你可以像这样访问项目:

ListView lv = (ListView) findViewById(R.id.MessageList);
lv.setAdapter(myAdapter);
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        MyClassWithGettersSetters objectClicked = (MyClassWithGettersSetters) myAdapter.getItem(arg2);
        Log.d(TAG, "Clicked on object: " + objectClicked);
        objectClicked.getDBID(); // you now have access to the specific object and id
        // do whatever you need to do
    }
});
于 2013-06-14T15:34:10.350 回答
0

创建视图时,将数据库 ID 设置为视图上的标记。在您的 onclick 中,您可以调用 arg1.getTag() 并取回该值。

于 2013-06-14T15:16:48.560 回答