0

I am trying to achieve a dynamic layout where there are 2 fragments (1 takes up the top 80% of the screen, and the other takes up the bottom 20% of the screen), and I want to be able to dynamically hide the bottom fragment and stretch the top fragment to fill the screen.

If there's an alternative way of doing it I'd like to know, but for now I only know of 1 way to do it. So I have 2 FrameLayouts and I am trying to set the layout_weight of the top FrameLayout (main_container) to 5.

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.jobby.jobbydriver.activity.main"
    android:id="@+id/activity_main"
    android:orientation="vertical"
    android:background="@color/ColorBG"
    android:weightSum="5"
    android:layout_height="match_parent"
    android:layout_width="match_parent" >
    <FrameLayout
        android:id="@+id/main_container"
        android:layout_weight="4"
        android:layout_height="0dp"
        android:layout_width="match_parent" />
    <FrameLayout
        android:id="@+id/second_container"
        android:layout_weight="1"
        android:layout_height="0dp"
        android:layout_width="match_parent" />
</LinearLayout>

my code,

FrameLayout frameLayout = findViewById(R.id.main_container);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) frameLayout.getLayoutParams();
params.weight = 5.0f; // "weight" is red, (Cannot resolve symbol 'weight')
frameLayout.setLayoutParams(params);

At the 2nd line from the bottom, params.weight is showing up in red, so weight is not a value of params here. This works for LinearLayout, but not FrameLayout, so I'm not sure what I'm doing wrong.

1 Answers1

0

When you try to get any view/viewgroups layout params it will give its parent's layout param.

By considering this you will get a LenearLayout.LayoutParams not FrameLayout.LayoutParams.

So, try this:

    FrameLayout frameLayout = findViewById(R.id.main_container);
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) frameLayout.getLayoutParams();
    params.weight = 5.0f;
    frameLayout.setLayoutParams(params);

NB: you already set weightsum 5. So, also consider to change other view weight.

Sayem
  • 4,891
  • 3
  • 28
  • 43
  • Nice, this way is much better than the top answer in the duplicate post because this way only requires me to set the weight. And I'll consider whether it's better to change the other view's visibility or change its weight or both. –  Jan 19 '18 at 13:07