以编程方式在 PercentageRelativeLayout 中设置纵横比

Set aspect ratio in PercentageRelativeLayout programmatically

我想以编程方式在 PercentRelativeLayout 中为我的 FrameLayout 设置纵横比。

我已经在 xml 中尝试过,它正在运行:

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

但我需要以编程方式设置它。

我该怎么做?

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

来自@azizbekian 的回答我只是详细说明了我的回答,

不使用分数,设置百分比的浮点值:

 PercentRelativeLayout.LayoutParams params = (PercentRelativeLayout.LayoutParams) mFlPromoVideoContainer.getLayoutParams();
        PercentLayoutHelper.PercentLayoutInfo info = params.getPercentLayoutInfo();
        info.widthPercent = 1f;
        info.aspectRatio = 1.78f;//178%
        mFlPromoVideoContainer.requestLayout();

您在 XML 中指定分数是这样的:

<item name="aspect_ratio" type="fraction">178%</item>

在Java,

 PercentRelativeLayout.LayoutParams params = (PercentRelativeLayout.LayoutParams) mFlPromoVideoContainer.getLayoutParams();
        PercentLayoutHelper.PercentLayoutInfo info = params.getPercentLayoutInfo();
        info.widthPercent = 1f;
        info.aspectRatio = getResources().getFraction(R.fraction.aspect_ratio, 1, 1);
        mFlPromoVideoContainer.requestLayout();