【问题标题】:get height size ( in pixel ) of a ViewGroup ( RecyclerView child of LinearLayout ) in runtime在运行时获取 ViewGroup(LinearLayout 的 RecyclerView 子项)的高度大小(以像素为单位)
【发布时间】:2016-12-30 06:57:44
【问题描述】:

我有一个主要的LinearLayout 和两个RecyclerView 作为孩子,需要获得第二个RecyclerView 的高度大小

我尝试了rv_show_adv.getHeight()rv_show_adv.getLayoutParams().height,但得到了0,但是当我在真实设备中测试应用程序时,我可以看到两者都有高度和宽度,但为什么在Java 代码中我总是得到0 像素!


/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>


真的很困惑,因为当我有一个视图(如TextView)时,我可以通过View.getHeight() 获得高度,但是当我有一个ViewGroup 时为什么不工作

我也尝试通过LinearLayout.getChildAt(1).getHeight() 获得主要LinearLayout 的第二个孩子的高度,但再次获得我0

还尝试在 onCreate() 中定义 RecyclerView 变量,并希望在 onResume() 生命周期中获得高度,但没有什么不同!

我想我在我的代码中遗漏了一些东西你有什么建议?

【问题讨论】:

    标签: android android-layout android-recyclerview viewgroup


    【解决方案1】:

    因为onCreate 上的View.getHeight() 为0,所以在onCreateView 时查看需要onMeasure()
    所以onMeasure() 可能在onCreated 之后完成,你应该这样做:

    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();
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      • 1970-01-01
      • 1970-01-01
      • 2015-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多