Android layout 布局转换导致Android崩溃

Android layout 布局转换导致Android崩溃,android-layout,casting,Android Layout,Casting,Android Studio 1.1.0、java 8、Windows 7 pro 64位 我的应用程序因运行时致命异常而崩溃,日志中出现以下错误。 java.lang.ClassCastException:android.widget.RelativeLayout$LayoutParams不能强制转换为android.widget.LinearLayout$LayoutParams 如果我注释掉java文件中的第二行,它不会崩溃。但我如何解决这个问题,我没有看到这样的铸造发生在我的代码 多谢各

Android Studio 1.1.0、java 8、Windows 7 pro 64位

我的应用程序因运行时致命异常而崩溃,日志中出现以下错误。 java.lang.ClassCastException:android.widget.RelativeLayout$LayoutParams不能强制转换为android.widget.LinearLayout$LayoutParams

如果我注释掉java文件中的第二行,它不会崩溃。但我如何解决这个问题,我没有看到这样的铸造发生在我的代码

多谢各位

    RelativeLayout headerSection = (RelativeLayout)findViewById(R.id.contact_view_header); //fetch the layout
    headerSection.setLayoutParams(new RelativeLayout.LayoutParams(width, (int) (width * (9.0 / 16.0))));
这是xml文件

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="au.com.totalcareauto.sam.mycontacts.ContactViewActivity">

<RelativeLayout
    android:id="@+id/contact_view_header"
    android:layout_width="match_parent"
    android:layout_height="200dp">
    <ImageView
        android:id="@+id/contact_view_image"
        android:src="@mipmap/sunset"
        android:scaleType="centerCrop"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    <TextView
        android:id="@+id/contact_view_name"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="@dimen/vertical_margin_small"
        android:textAppearance="@style/TextAppearance.AppCompat.Display1"
        android:textColor="@android:color/white"
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <android.support.v7.widget.Toolbar
        android:id="@+id/contact_view_toolbar"
        android:fitsSystemWindows="true"
        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        android:minHeight="?attr/actionBarSize"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

<ListView
    android:id="@+id/contact_view_fields"
    android:layout_width="match_parent"
    android:layout_weight="100"
    android:layout_height="0dp" />

您对LayoutParams子类的选择是错误的

布局参数的正确形式应取决于LinearLayout而不是RelativeLayout,因为LinearLayout是您案例中的父视图,RelativeLayout是子视图

因此,可以使用LinearLayout.LayoutParams而不是RelativeLayout.LayoutParams,也可以使用RelativeLayout作为根视图

 RelativeLayout headerSection = (RelativeLayout)findViewById(R.id.contact_view_header); //fetch the layout
 headerSection.setLayoutParams(new LinearLayout.LayoutParams(width, (int) (width * (9.0 / 16.0))));
我想这会解决你的问题。我已经测试过了,效果很好