无法为包含显示类强制转换异常的文件中的相对布局动态设置布局参数

时间:2016-07-20 10:56:23

标签: android android-layout android-include

     <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/parentLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="">
    <include android:id="@+id/contentLayout" layout="@layout/content_our_story" />
</android.support.design.widget.CoordinatorLayout>

content_our_story.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=""
    android:layout_margin="5dp"
    tools:showIn="@layout/activity_our_story">


</RelativeLayout>

设置布局参数代码:

contentLayout = (RelativeLayout) findViewById(R.id.contentLayout);
  RelativeLayout.LayoutParams param=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        param.setMargins(0,0,0,0);
        contentLayout.setLayoutParams(param);

当我尝试使用&#34; contentLayout&#34;的id设置LayoutParams时它显示了类强制转换异常并期望它成为协调器布局。但是,它包含如上所示的相对布局。建议。

1 个答案:

答案 0 :(得分:1)

您需要使用要将params设置为的父视图布局的LayoutParams:

CoordinatorLayout.LayoutParams param=new CoordinatorLayout.LayoutParams(CoordinatorLayout.LayoutParams.MATCH_PARENT, CoordinatorLayout.LayoutParams.MATCH_PARENT);