Android PercentRelativeLayout width won't change with ratio when layout changed

875 Views Asked by At

I'm trying to make a textureview keep the 16:9 ratio when layout changes. I use percentrelativelayout to implement it. Also I need the textureview not exceed the screen size both on width/height. So I use 2 layers to make sure it won't exceed the screen.

It resize perfectly on layout preview in android studio. But the width isn't changing to keep the ratio in runtime on the device.

Here's the layout xml and the screenshot.

Have someone met the same question?

<android.support.percent.PercentRelativeLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:gravity="center">

    <android.support.percent.PercentRelativeLayout
        android:id="@+id/percent"
        app:layout_aspectRatio="178%"
        app:layout_widthPercent="100%"
        android:background="@android:color/darker_gray">
        <TextureView
            android:id="@+id/texture"
            app:layout_aspectRatio="178%"
            app:layout_heightPercent="100%"
            android:layout_centerInParent="true">
        </TextureView>
    </android.support.percent.PercentRelativeLayout>

</android.support.percent.PercentRelativeLayout>

One layout in the bottom is set to VISIBLE

After bottom layout set to GONE

1

There are 1 best solutions below

2
On

I had to play around with these PercentRelativeLayouts to get the result I was looking for too. Below is the code I used to get the same result you are looking for except I used a fragment. I've tested this on multiple devices and it worked on all of their different screen sizes. In your case, I would suggest replacing my "article_preview_frame" FrameLayout with your TextureView and see where that gets you. Make sure that you embed your PercentRelativeLayout inside a regular RelativeLayout.

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/article_preview_relative_layout"
>

<android.support.percent.PercentRelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/article_preview_container">

    <FrameLayout
        app:layout_widthPercent="100%"
        app:layout_aspectRatio="178%"
        android:layout_alignParentTop="true">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/article_preview_frame"
            />