我有一个带有自定义适配器(基本适配器)的listview。我想通过位置从listview获取视图。我试过mListView.getChildAt(position)
,但它不工作。如何按位置获取项目视图?
发布于 2014-07-21 19:57:53
使用以下命令:
public View getViewByPosition(int pos, ListView listView) {
final int firstListItemPosition = listView.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition ) {
return listView.getAdapter().getView(pos, null, listView);
} else {
final int childIndex = pos - firstListItemPosition;
return listView.getChildAt(childIndex);
}
}
发布于 2014-07-18 03:46:37
您只能从ListView获取可见视图,因为ListView中的行视图是可重用的。如果你使用mListView.getChildAt(0)
,你会得到第一个可见的视图。此视图与位置mListView.getFirstVisiblePosition()
处的适配器中的项目相关联。
发布于 2014-07-18 03:56:18
绘制ListView后更改行视图外观的首选方法是更改ListView从中提取的数据(传递到适配器的对象数组)中的某些内容,并确保在getView()函数中考虑到这一点,然后通过调用
notifyDataSetChanged();
编辑:虽然有一种方法可以做到这一点,但如果你需要这样做,你很可能做错了什么。虽然我能想到的边缘情况很少,但通常使用notifyDataSetChanged()
和其他内置机制是一种可行的方法。
编辑2:人们经常犯的一个错误是试图想出自己的方式来响应用户在ListView中点击/选择行,正如本文的一条评论所示。有一种现有的方法可以做到这一点。下面是操作步骤:
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
/* Parameters
parent: The AdapterView where the click happened.
view: The view within the AdapterView that was clicked (this will be a view provided by the adapter)
position: The position of the view in the adapter.
id: The row id of the item that was clicked. */
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//your code here
}
});
ListView有很多内置功能,没有必要为更简单的情况重新发明轮子。因为ListView扩展了AdapterView,所以您可以设置相同的侦听器,比如上面示例中的OnItemClickListener。
https://stackoverflow.com/questions/24811536
复制相似问题