从行listview获取id

时间:2014-08-17 07:01:40

标签: android listview

lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long rid) {

                lv.getAdapter().getItem(position);
                Intent intent = new Intent(getActivity()
                        .getApplicationContext(), RestaurantActivity.class);
                intent.putExtra("restaurant_id", restid);
                startActivity(intent);

            }
        });

lv.getAdapter().getItem(position)给我

{number_of_orders=1 offer, restaurant_id=5, distance=5.0 km, restaurantname=Brookside}

我只想要restaurant_id值,即5。

那么,如何从行 listview 获取id(id通过mysql json响应填充)android 我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

以下一行:

lv.getAdapter().getItem(position)

会返回Object,其类型与您Adapter的类型相同。例如,使用此适配器:

ArrayAdapter<MyObject> adapter = new ArrayAdapter<MyObject>(...);

收集的对象将是MyObject

因此,如果您只想获得restaurant_id,则只需在MyObject类中添加一个getter,该类将返回id:

public class MyObject {
    private int id;
    ...
    public int getId() {
        return id;
    }
    ...
}

然后当你想获得这个id时,你可以这样做:

MyObject myObject = (MyObject) lv.getAdapter().getItem(position);
int id = myObject.getId();