在Listview适配器中获取子视图

时间:2013-03-04 11:48:10

标签: android android-listview

在我的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对象中获取特定视图?

2 个答案:

答案 0 :(得分:3)

  

我知道我的适配器通过调用来保存多个项目   getCount将:

是的,但适配器的getCount()(返回适配器中的项)方法与使用{ListView的子项无关{1}}(您应该使用getChildAt(),因为这会返回getChildCount() 中的Views

  

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

这应该返回一个非空视图,即ViewGroup方法返回的最后一个视图。

  

我只想在我的ViewGroup中为特定视图制作动画

如果要在列表行(或该行的一部分)变为可见时为其设置动画,而不是为getView()注册滚动侦听器,并在目标视图出现在屏幕上时从那里开始动画

答案 1 :(得分:0)

我不知道你是如何实现适配器的其余部分的,但是如果你以正确的方式实现它,我是对的,那么父节点只包含在设备屏幕上显示的视图,每次你下拉或拉出列表,它会修改这些视图的内容,这就是你得到Null的原因。

您想要实现的内容(为视图设置动画)应该在运行时完成,检查当前显示在屏幕上的视图是否应该设置动画。

希望它有所帮助。