[英]Android: get position of item in a listview given its id:
getItemIdAtPosition()
是android中的一個函數,用於獲取列表視圖中項目的id給定其位置
有沒有辦法做反過來,即獲取項目的位置是一個列表視圖給定其ID?
不,你必須手動完成。 在您正在使用的適配器中創建一個公共方法; 在該方法中,循環適配器項並檢查每個項ID。 如果= =方法參數,則返回索引。
public int getItemPosition(long id)
{
for (int position=0; position<mList.size(); position++)
if (mList.get(position).getId() == id)
return position;
return 0;
}
更新:如果查找性能代表您的用例問題,您也可以在適配器中保存位置/ ID的HashMap。
更新:如果要在適配器外使用此方法,請使用以下內容:
private int getAdapterItemPosition(long id)
{
for (int position=0; position<mListAdapter.getCount(); position++)
if (mListAdapter.get(position).getId() == id)
return position;
return 0;
}
不確定問題是否仍然存在。 盡管如此,我想我會分享我是如何做到的,以便它可以幫助那些想要做同樣事情的人。
您可以使用視圖的標記功能來存儲該視圖的id與其在列表中的位置之間的映射。
android開發者網站上的標簽文檔很好地解釋了它:
http://developer.android.com/reference/android/view/View.html#Tags
http://developer.android.com/reference/android/view/View.html#setTag(int,java.lang.Object)
http://developer.android.com/reference/android/view/View.html#getTag(int)
示例:在列表適配器的getView方法中,您可以設置該視圖的id及其在列表中的位置的映射,例如:
public View getView (int position, View convertView, ViewGroup parent)
{
if(convertView == null)
{
// create your view by inflating a xml layout resource or instantiating a
// custom view class
}
else
{
// Do whatever you want with the convertView object like
// finding a child view that you want to set some property of,etc.
}
// Here you set the position of the view in the list as its tag
convertView.setTag(convertView.getId(),position);
return convertView;
}
要檢索視圖的位置,您可以執行以下操作:
int getItemPosition(View view)
{
return view.getTag(view.getId());
}
需要注意的一點是,您需要引用要查找其位置的視圖。 如何掌握View的參考取決於您的具體情況。
不會。根據您用來支持ListView
的適配器,id和位置可能是相同的(我沒有查看所有BaseAdapter
子類,所以我不能肯定地說)。 如果查看ArrayAdapter的源代碼,您會看到getItemId
實際上返回了適配器中對象的位置。 如果position和id相同,則不需要使用一個來獲取另一個。 否則,您只需要在適配器中搜索您要查找的對象 - 使用位置或ID - 您就可以找到其他值。
如果您正在談論的是使用一些獨特的密鑰(即您定義的密鑰)來獲取對象,那么就可以完成。 您需要做的是設置適配器以獲取HashMap
而不是ArrayList
或常規的對象List
。 然后,您可以通過簡單地從HashMap
提取該值來創建自己的方法來按鍵查找。
回答為時已晚,但為了受益......
例如,如果你有listview,並且你想獲得點擊監聽器的id,你可以通過>>獲得它
cListview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// for id or any informations
itemID = String.valueOf(catList.get(position).getItemID());
// for name or any informations
itemName = String.valueOf(catList.get(position).getItemName());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.