Muhammad Umar
Muhammad Umar

Reputation: 11782

ClassCastException when trying to Add HeaderView to listView android

I am trying to add HeaderView to my EndlessListView

Here is the code

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);

I am getting this error

 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)

If i put null instead of bgLayout or return true, it gives me error

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

Upvotes: 2

Views: 248

Answers (1)

andrew
andrew

Reputation: 6563

You are getting error cause you are inflating layout in wrong way. Let's take a look to documentation:

public View inflate (int resource, ViewGroup root, boolean attachToRoot)

root Optional view to be the parent of the generated hierarchy (if attachToRoot is true), or else simply an object that provides a set of LayoutParams values for root of the returned hierarchy (if attachToRoot is false.)

So, you are specifying RelativeLayout as paretnt and RelativeLayout.LayoutParams are taking from that layout. After that you are trying to add that view to ListView which useses AbsListView.LayoutParams layout params.

You should be able to add footer by inflating it with ListView specified as parent instead mainLayout

Upvotes: 2

Related Questions