get height size ( in pixel ) of a ViewGroup ( RecyclerView child of LinearLayout ) in runtime

1.6k views Asked by At

i have a main LinearLayout and two RecyclerView as child and need to get height size of second RecyclerView

i tried by rv_show_adv.getHeight() and rv_show_adv.getLayoutParams().height but get me 0 but when i test the app in a real device i could to see i have height and width on both but why in java code i always got 0 pixel !

enter image description here


/layout/activity_main.xml :

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/mainlinear"
        android:orientation="vertical"
        tools:context=".main.MainActivity"
        android:background="#f3cdcd"
        android:weightSum="1"
        >

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="55dp"
            >

            <android.support.v7.widget.RecyclerView
                android:id="@+id/rv_selected_adv"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

            </android.support.v7.widget.RecyclerView>

        </LinearLayout>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_show_adv"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:background="#b9f1ce"
            android:layout_weight="1">

        </android.support.v7.widget.RecyclerView>

    </LinearLayout>


really confused because when i have a View (like as TextView) i could to get height by View.getHeight() but why not worked when i had a ViewGroup

i also try to get height of second child of main LinearLayout by LinearLayout.getChildAt(1).getHeight() but again get me 0

also try to define RecyclerView variable in onCreate() and wants to get height in onResume() lifecycle but not different!

i think i miss somethings in my code what do you suggestion ?

1

There are 1 answers

0
Yat3s On BEST ANSWER

Because of View.getHeight() on onCreate is 0, view need onMeasure() when onCreateView
so onMeasure() maybe finished after onCreated, you should do this:

int mWidth , mHeight ;
rv_show_adv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            rv_show_adv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        } else {
            rv_show_adv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }
        mWidth = rv_show_adv.getWidth();
        mHeight = rv_show_adv.getHeight();
    }
});