Home » Android » android:layout_weight="33" how does gone->visible visible->gone effect this?

android:layout_weight="33" how does gone->visible visible->gone effect this?

Posted by: admin June 15, 2020 Leave a comment

Questions:

android layouts use a layout_weight. I am aiming for 1/3 for all components but sometimes the footer is literally set to gone, and then visible. How does the weight calculation work when setting from gone to visible? I am not seeing the content inside a linear layout which has 1/3 weight?

How to&Answers:

It appears to be necessary to call refreshDrawableState() on a view after changing its weight for the change to be rendered:

((LinearLayout.LayoutParams) btnFav.getLayoutParams()).weight = 3f;
btnFav.refreshDrawableState();

Answer:

make sure you set height to 0dp and then set the weight on all of the views to 1

ie

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="Hello World, MyActivity"
        android:background="#f00"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="Hello World, MyActivity"
        android:background="#00f"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="Hello World, MyActivity"
        android:background="#0f0"
        />
</LinearLayout>

when a view is set to gone the remaining views will fill up their ratio of the screen. Ie if you set the third view to gone the first 2 views will take up 50% each of the available space in the layout

Furthermore, if you want the remaining views to only take up 1/3 of space each (ie 2/3 used and leave 1/3 empty) set your hidden view to invisible not gone