我的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"/>
现在我想通过java代码设置Listview
的高度。我尝试使用以下代码。
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
。我的代码有什么问题?
答案 0 :(得分: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),而不是根据您先前导入的LayoutParams类进行Eclipse猜测。
您可以看到此previous question以获取更多信息。
答案 1 :(得分:0)
在这一行:new ListView.LayoutParams(LayoutParams.FILL_PARENT, 500)
你混淆了LayoutParams类。
要么
new ListView.LayoutParams(ListView.LayoutParams.FILL_PARENT, 500)
或
new LayoutParams(LayoutParams.FILL_PARENT, 500)
会解决这个问题。