简体   繁体   English

如何从Android中的“自定义ListView”获取被点击项的位置?

[英]How to get clicked item position from Custom ListView in android?

I'm trying to get the position of the custom list view (after sorted from original list position). 我正在尝试获取自定义列表视图的位置(从原始列表位置排序后)。 It is because the database id of the list item matches the position of the listview item. 这是因为列表项的数据库ID与listview项的位置匹配。 so, i need to get the sorted item's correct position matching the listview item position. 因此,我需要获取与listview项目位置匹配的已排序项目的正确位置。 I have this code. 我有这个代码。

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return sampleArrayList.get(position);
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

But im struck out that i need to get that position into my main activity. 但是我惊讶地发现,我需要将该职位纳入我的主要活动。 Any help is really appreciated and thanks in advance... 非常感谢您的任何帮助,并在此先感谢...

I doubt,I completely understand your problem and what you want exactly.But i can suggest you that you can maintain HashMap for storing position-id pairs for each listview. 我怀疑,我完全理解您的问题以及您想要的是什么。但是我建议您可以维护HashMap以便为每个列表视图存储位置ID对。

in your CustomAdapter: 在您的CustomAdapter中:

public static HashMap<Integer,String> myList=new HashMap<Integer,String>();

in getView(): 在getView()中:

String id= (fetch _id from database);
myList.put(position, id);

And now in your main acitivity,you can retrieve _id of each listitem by putting this line in onClick() of OnItemClickListener(): 现在,在您的主要活动中,您可以通过将以下行放在OnItemClickListener()的onClick()中来检索每个listitem的_id:

 Long id=Long.parseLong(CustomAdapter.myList.get(position));

You can define a field in the custom adapter mCurrentPosition, set it int the method 您可以在自定义适配器mCurrentPosition中定义一个字段,并将其设置为int方法

View getView(final int position, View convertView, ViewGroup parent) {<
this.mCurrentPosition = position;
....
}

Access this field from the activity. 从活动中访问此字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM