在Listview适配器中获取子视图

3

在我的getView方法中,我想获取特定的子视图。我知道我的适配器包含多个项目,通过调用getCount:

getCount();

根据JavaDoc:
public abstract int getCount () 
Added in API level 1
How many items are in the data set represented by this Adapter.

现在在我的getView方法中:
public View getView(final int position, View convertView, ViewGroup parent) {

   View lastAddedItem = parent.getChildAt(getCount()-1);
   if(lastAddedItem == null)  {
     Log.w("ListAdapter", "View is null");
   }

}

这个消息总是出现在 LogCat 中,意味着我试图获取的视图是 null

我也尝试过这样做:

View lastAddedItem = parent.getChildAt(parent.getChildCount()-1);

那么如何从我的 ViewGroup 对象中获取特定的视图?

你不想这样做...相信我...你想要实现什么? - Selvin
我只想在我的ViewGroup中动画一个特定的“View”。为什么这是不好的实践?我只是复制了这个视图并对其进行操作。 - Tobias Moe Thorstensen
据我所知,它总是会返回 null.. 因为 ListView 的行为是回收视图。因此,您的视图没有在屏幕上绘制,因此为 null。 - Pragnani
2个回答

3
我知道我的适配器包含多个项目,可以通过调用 getCount() 方法来获取它们:
是的,但是适配器的 getCount() 方法(返回适配器中的项目)与使用 getChildAt() 获取 ListView 的子项(应该使用 getChildCount(),因为它将返回 ViewGroup 中存在的 View)无关。 lastAddedItem = parent.getChildAt(parent.getChildCount()-1);
这应该返回一个非空视图,即 getView() 方法返回的最后一个视图。
我只想在我的 ViewGroup 中动画特定的 View
如果您要在列表行(或该行的一部分)出现时对其进行动画处理,则应为 ListView 注册滚动侦听器,并在目标视图出现在屏幕上时从那里开始动画。

0

我不知道你是如何实现适配器的其余部分的,但如果你是以正确的方式进行的,并且我是正确的,那么父级仅包含在设备屏幕上显示的视图,每次你向下或向上拉列表时,它会修改这些视图的内容,这就是为什么你会得到Null。

你想要实现的(动画一个视图),应该在运行时完成,检查当前在屏幕上显示的视图是否应该被动画化。

希望能有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接