Leon Lucardie
Leon Lucardie

Reputation: 9730

Cast exception on my custom Adapter

I'm currently having a issue with the Android ListView in Monodroid.

I initialize and set up the list with a custom adapter like this:

ListView setting_listview = new ListView(this);
//Components and layoutparameters is done here

RelativeLayout bottom_view = new RelativeLayout(this);
//Components/layoutparameters is done here
setting_listview.AddFooterView(bottom_view);

TTListAdapter adapter = new TTListAdapter(this, listdata, Resource.Layout.datatable_list_item,secList);
setting_listview.Adapter = adapter;

Now when I try to retrieve the Adapter in another piece of code like this:

TTListAdapter adapter = (TTListAdapter)setting_listview.Adapter;

I get the following exception: System.InvalidCastException: Cannot cast from type HeaderViewListAdapter to TTListAdapter. Apparantly the Adapter property now returns a HeaderViewListAdapter instead of the expected TTListAdapter that was set during initialisation.

If I do not use AddFooterView during the initialisation it will return the original TTListAdapter that was set during initialisation.

Why does the Adapter property return a HeaderViewListAdapter instead of the originally set Adapter after AddFooterView has been called and how can I retrieve the original Adapter if this happens?

EDIT: Rephrased part of the question to make it a little clearer

Upvotes: 1

Views: 452

Answers (1)

Leon Lucardie
Leon Lucardie

Reputation: 9730

After experimenting some more with the HeaderViewListAdapter I found out that whenever a ListView had header or footer views. It automatically wraps the original adapter in a HeaderViewListAdapter which will manage those headers and footers. The original Adapter can then be retrieved by calling the WrappedAdapter property in the HeaderViewListAdapter class.

Example for my case:

HeaderViewListAdapter adapter = (HeaderViewListAdapter)this.setting_listview.Adapter;
TTListAdapter origAdapter = (TTListAdapter)adapter.WrappedAdapter;

Upvotes: 4

Related Questions