androidandroid-layoutandroid-include

Cannot dynamically set Layout parameters for Relative layout present inside include file showing class cast exception


     <?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>

setting layout param code:

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);

When I try to set LayoutParams using id of "contentLayout" it shows class cast exception and expects it to be a coordinator layout. However, it contains relative layout as shown above.Do suggest.


Solution

  • You need to use LayoutParams of parent layout of view you want to set params to:

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