Error java.lang.ClassCastException: android.view.ViewGroup$L



我已经开始使用android应用程序,我设计的布局是这样的RelativeLayoutGridView的父级,我只想以编程方式设置GridViewLayoutParams

以下是我正在做的布局和代码:

布局.xml

<?xml version="1.0" encoding="utf-8"?>
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="fill_parent" >
      <RelativeLayout
          xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/relativeLayout"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content" 
          android:background="#FFFFFF">
       <GridView
           xmlns:android="http://schemas.android.com/apk/res/android"
           android:id="@+id/gridview"
           android:layout_width="fill_parent"
           android:layout_height="510dp"
           android:gravity="center"
           android:horizontalSpacing="@dimen/image_grid_hspacing"
           android:numColumns="@integer/grid_num_cols"
           android:stretchMode="columnWidth"
           android:verticalSpacing="@dimen/image_grid_vspacing"
           android:background="#FFFFFF" />   
       </RelativeLayout>
    </ScrollView>

法典:

GridView gridview = (GridView) rootView.findViewById (R.id.gridview);
gridview.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 300));

当我启动我的应用程序时,它总是崩溃并且错误日志猫说

错误 java.lang.ClassCastException: android.view.ViewGroup$LayoutParams

很抱歉有一个愚蠢的问题,我不知道它抛出异常的原因。请分享您对例外

从 xml 布局的外观来看,您的 GridView 具有父级RelativeLayout,因此您必须使用 RelativeLayout.LayoutParams

gridview.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, 300));

此外,避免在ScrollView中使用GridView,因为如果孩子无法适应屏幕,GridView会自行处理滚动。

相关内容

最新更新