0

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?

Onik
  • 19,396
  • 14
  • 68
  • 91
Magesh Pandian
  • 8,789
  • 12
  • 45
  • 60

2 Answers2

3
PercentRelativeLayout layout = ...;
PercentRelativeLayout.LayoutParams layoutParams 
           = (PercentRelativeLayout.LayoutParams) layout.getLayoutParams();
layoutParams.getPercentLayoutInfo().aspectRatio = ...; // float value
layout.requestLayout();
azizbekian
  • 60,783
  • 13
  • 169
  • 249
  • Thank for your answer. But What is the float value ?. I need to set 178% as float. – Magesh Pandian Mar 20 '17 at 08:40
  • You can see how that value is counted [in the sources](https://github.com/android/platform_frameworks_support/blob/master/percent/src/android/support/percent/PercentLayoutHelper.java#L234). – azizbekian Mar 20 '17 at 08:46
0

From @azizbekian Answer just i elaborate my answer,

Without using fractions, set float value of percentage :

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

You specify fractions in XML as so:

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

In 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();
Magesh Pandian
  • 8,789
  • 12
  • 45
  • 60