【问题标题】:Error java.lang.ClassCastException: android.view.ViewGroup$LayoutParams错误 java.lang.ClassCastException: android.view.ViewGroup$LayoutParams
【发布时间】:2012-10-05 08:28:18
【问题描述】:

我已经开始工作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));

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

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

对不起一个愚蠢的问题,我不知道它抛出异常的原因。请分享您对例外情况的可能性问题的看法

【问题讨论】:

    标签: android android-layout gridview


    【解决方案1】:

    您只放置存在于所有 ViewGroup 对象中的 LayoutParams。所以需要说清楚GridView属于哪个ViewGroup Object。

    你改变你的代码如下,

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

    【讨论】:

      【解决方案2】:

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

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

      另外,避免在ScrollView 中使用GridView 作为GridView 在屏幕上无法容纳子元素时自行处理滚动。

      【讨论】:

        猜你喜欢
        • 2013-11-05
        • 1970-01-01
        • 2023-03-23
        • 1970-01-01
        • 2017-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多