我需要找到使用ListView
显示的列表中一个元素的像素位置。似乎应该获取一个TextView,然后使用getTop()
,但我无法弄清如何获取ListView
的子视图。
更新: 对于ListView
,ViewGroup
的子项与列表中的项目不是一一对应的。相反,ViewGroup
的子项仅对应当前可见的视图。因此,getChildAt()
操作的是ViewGroup
内部的索引,并不一定与ListView
使用的列表位置有任何关系。
我需要找到使用ListView
显示的列表中一个元素的像素位置。似乎应该获取一个TextView,然后使用getTop()
,但我无法弄清如何获取ListView
的子视图。
更新: 对于ListView
,ViewGroup
的子项与列表中的项目不是一一对应的。相反,ViewGroup
的子项仅对应当前可见的视图。因此,getChildAt()
操作的是ViewGroup
内部的索引,并不一定与ListView
使用的列表位置有任何关系。
参见:Android ListView:获取可见项的数据索引 再结合以上Feet回答的部分内容,您可以得到如下内容:
int wantedPosition = 10; // Whatever position you're looking for
int firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount(); // This is the same as child #0
int wantedChild = wantedPosition - firstPosition;
// Say, first visible position is 8, you want position 10, wantedChild will now be 2
// So that means your view is child #2 in the ViewGroup:
if (wantedChild < 0 || wantedChild >= listView.getChildCount()) {
Log.w(TAG, "Unable to get view for desired position, because it's not being displayed on screen.");
return;
}
// Could also check if wantedPosition is between listView.getFirstVisiblePosition() and listView.getLastVisiblePosition() instead.
View wantedView = listView.getChildAt(wantedChild);
好处是你不会遍历ListView的子元素,这可能会影响性能。
这段代码更易于使用:
View rowView = listView.getChildAt(viewIndex);//The item number in the List View
if(rowView != null)
{
// Your code here
}
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
View v;
int count = parent.getChildCount();
v = parent.getChildAt(position);
parent.requestChildFocus(v, view);
v.setBackground(res.getDrawable(R.drawable.transparent_button));
for (int i = 0; i < count; i++) {
if (i != position) {
v = parent.getChildAt(i);
v.setBackground(res.getDrawable(R.drawable.not_clicked));
}
}
}
});
int position = 0;
listview.setItemChecked(position, true);
View wantedView = adapter.getView(position, null, listview);
这假设您知道ListView中元素的位置:
View element = listView.getListAdapter().getView(position, null, null);
然后您应该能够调用 getLeft() 和 getTop() 方法来确定元素在屏幕上的位置。
getView()
将被内部调用。您不应该在该位置使用它来获取列表中的视图,因为如果使用null作为convertView
参数调用getView()
,则会导致适配器从适配器的布局资源中膨胀出一个新视图(而不是获取已经显示的视图)。 - Joe
firstPosition
的代码更改为int firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount();
可以解决这个问题。 - pospiListView
已经处理了“移动”旧convertView
后围绕着子视图的操作,因此您可以保证ListView.getChildAt(0)
实际上是适配器中第一个附加的视图。它可能不是完全可见的(也可能根本不可见,这取决于ListView
在回收它认为“滚出视图”的视图之前的“可见性”阈值)。 - Joeadapter.notifyDataSetChanged()
并让适配器重新创建视图(并更新必要的内容)。但无法手动更改视图。 - Teo Inke