Search code examples
javaandroidandroid-layoutandroid-viewandroid-percentrelativelayout

Set aspect ratio in PercentageRelativeLayout programmatically


I want to set aspect ratio for my FrameLayout inside PercentRelativeLayout programmatically.

I already tried in xml, it's working:

<android.support.percent.PercentRelativeLayout 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="#000"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <FrameLayout
        app:layout_widthPercent="100%"
        app:layout_aspectRatio="178%" //aspect ratio
        android:orientation="vertical"
        android:id="@+id/liveTV_frame"
        android:layout_marginBottom="50dp"
        android:layout_centerInParent="true"
        android:background="@android:color/background_dark"
        android:keepScreenOn="true">
    </FrameLayout>
</android.support.percent.PercentRelativeLayout>

But I need to set it programmatically.

How can I do that?


Solution

  • PercentRelativeLayout layout = ...;
    PercentRelativeLayout.LayoutParams layoutParams 
               = (PercentRelativeLayout.LayoutParams) layout.getLayoutParams();
    layoutParams.getPercentLayoutInfo().aspectRatio = ...; // float value
    layout.requestLayout();