尝试将HeaderView添加到listView android时出现ClassCastException

时间:2015-03-07 12:46:04

标签: java android eclipse

我正在尝试将HeaderView添加到我的EndlessListView

这是代码

mainLayout is the parent of SwipeLayout in which ListView is placed
ViewGroup headerView = (ViewGroup) getLayoutInflater().inflate(R.layout.profile_header, (RelativeLayout) findViewById(R.id.mainLayout), false);
        listView.addHeaderView(headerView, null, false);
        adapter = new  TrafficTweatsAdapter(this, tweatsList);
        listView.setAdapter(adapter);

我收到此错误

 Caused by: java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams
            at android.widget.ListView.clearRecycledState(ListView.java:513)
            at android.widget.ListView.resetList(ListView.java:499)
            at android.widget.ListView.setAdapter(ListView.java:442)
            at com.app.custom.EndlessListView.setAdapter(EndlessListView.java:45)

如果我输入null而不是bgLayout或返回true,则会给出错误

java.lang.NullPointerException
            at android.widget.AbsListView.obtainView(AbsListView.java:2269)
            at android.widget.ListView.makeAndAddView(ListView.java:1769)

1 个答案:

答案 0 :(得分:1)

由于您以错误的方式给布局充气,您会收到错误。我们来看看documentation

  

public View inflate(int资源,ViewGroup root,boolean attachToRoot)

     

root可选视图是生成的层次结构的父级(如果attachToRoot为true),或者只是为返回的层次结构的根提供一组LayoutParams值的对象(如果attachToRoot为false。)

因此,您指定RelativeLayout为paretnt,RelativeLayout.LayoutParams正在从该布局中获取。之后,您尝试将该视图添加到使用ListView布局参数的AbsListView.LayoutParams

您应该能够通过将ListView指定为父级来代替mainLayout

来添加页脚