Android 布局高度问题与重量和包裹内容

Android 布局高度问题与重量和包裹内容,android,android-layout,Android,Android Layout,我的看法是: <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <RecyclerView android:layout_width="match_parent" android:layout_he

我的看法是:

<LinearLayout 
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="match_parent">

<RecyclerView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
/>

<TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        />
</LinearLayout>

它将为
TextView
提供50dp,并为
RecyclerView
提供其余区域。
但是如果
RecyclerView
中的项目小于,比如1或2,那么它应该收缩到它的子视图的高度,其他方面的行为就像布局指定的那样。有人能帮忙吗?

我认为最好的选择是动态更改根视图的
LinearLayout.LayoutParams
。当
RecyclerView
的子项数量较少时,请将
LinearLayout
参数设置为:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
layout.setParams(params);
否则,请保持原样

很容易检测是否应包装
RecyclerView
。获取线性布局高度:

int height = layout.getTop() - layout.getBottom()

如果此高度低于预期的最大高度(屏幕高度或其他预定义值)。

一个简单的方法是使用RelativeLayout:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_below="@+id/recyclerView" />

</RelativeLayout>


为什么不使用RelativeLayout并使用下面的属性布局?或者你不想这样?谢谢@HusseinElFeky