Android ListView layout param set

dev_android picture dev_android · Jul 21, 2011 · Viewed 17.1k times · Source

I have a Listview in my xml. The structure of it like that:

<ListView 
    android:id="@+id/SeriesCastListItemView"
    android:paddingTop="10dip"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:divider="#FFFFFF"
    android:dividerHeight="1px"/>

Now I want to set a height for the Listview by java code. i am tried with following code.

ListView castListItemView = (ListView) findViewById(R.id.SeriesCastListItemView);
castListItemView.setAdapter(new CastAdapter(this, castDescriptionArr));
castListItemView.setLayoutParams(new ListView.LayoutParams(LayoutParams.FILL_PARENT, 500));

But it giving java.lang.ClassCastException: android.widget.AbsListView$LayoutParams. What is the problem in my code?

Answer

theisenp picture theisenp · Jul 21, 2011

You should be using the LayoutParams of the parent view that contains your ListView. In my case, I placed the ListView in a Frame Layout, and used this code. If you placed the ListView in a LinearLayout you would use LinearLayout.LayoutParams.

ListView castListItemView = (ListView) findViewById(R.id.SeriesCastListItemView);
castListItemView.setAdapter(new CastAdapter(this, castDescriptionArr));
castListItemView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT, 500));

I assume it was a typo in your question, but make sure that the "c" in castListItemView is lowercase on your third line.

MrJre brings up a good point though. Because many different views have their own LayoutParams, it is best to include the view whose parameters you wish to use (as in FrameLayout.LayoutParams) instead of making Eclipse guess based on which LayoutParams class you previously imported.

You can see this previous question for more information.