0

我想以编程方式为我的FrameLayout内部设置纵横比PercentRelativeLayout

我已经尝试过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>

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

我怎样才能做到这一点?

4

2 回答 2

3
PercentRelativeLayout layout = ...;
PercentRelativeLayout.LayoutParams layoutParams 
           = (PercentRelativeLayout.LayoutParams) layout.getLayoutParams();
layoutParams.getPercentLayoutInfo().aspectRatio = ...; // float value
layout.requestLayout();
于 2017-03-20T08:38:02.577 回答
0

从@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();
于 2017-03-20T09:42:54.797 回答