2

我的 xml 中有一个 Listview。它的结构是这样的:

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

现在我想为Listviewby java 代码设置一个高度。我尝试使用以下代码。

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

但它给予java.lang.ClassCastException: android.widget.AbsListView$LayoutParams。我的代码有什么问题?

4

2 回答 2

8

您应该使用包含您的 ListView 的父视图的 LayoutParams。就我而言,我将 ListView 放置在 Frame Layout 中,并使用了此代码。如果您将 ListView 放在 LinearLayout 中,您将使用 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));

我认为这是您的问题中的拼写错误,但请确保 castListItemView 中的“c”在您的第三行是小写的。

MrJre 提出了一个很好的观点。因为许多不同的视图都有自己的 LayoutParams,所以最好包含您希望使用其参数的视图(如在 FrameLayout.LayoutParams 中),而不是让 Eclipse 根据您之前导入的 LayoutParams 类进行猜测。

您可以查看上一个问题以获取更多信息。

于 2011-07-21T14:11:41.383 回答
0

在这一行中:new ListView.LayoutParams(LayoutParams.FILL_PARENT, 500)您正在混合 LayoutParams 类。

任何一个

new ListView.LayoutParams(ListView.LayoutParams.FILL_PARENT, 500)

或者

new LayoutParams(LayoutParams.FILL_PARENT, 500)

将解决它是我的猜测。

于 2011-07-21T13:33:53.727 回答