如何设置RecyclerView的最大高度?

Anj*_*een 2 android relativelayout android-layout android-studio

我必须implementinga RecylerView,它应该包含内容,如果它只包含项目内容高度较少.如果项目的增加喜欢250dp,它应该设置为max heght(250dp)并且能够滚动.如何实现这个Relative layout.我的父布局是一个.

这是我的布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:layout_alignParentBottom="true"
        android:layout_gravity="bottom" />

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

屏幕截图,如果它只有一个项目.这应该是wrap_content.

屏幕截图,如果它只有一个项目.这应该是wrap_content.

raf*_*007 5

你可以将高度设置为 RecylerView

如果只有一个项目...... wrap content

ViewGroup.LayoutParams params=recycler_view.getLayoutParams();
params.height= RecyclerView.LayoutParams.WRAP_CONTENT;
recycler_view.setLayoutParams(params);
Run Code Online (Sandbox Code Playgroud)

其他

<dimen name="view_height">250dp</dimen>

float height= getResources().getDimension(R.dimen.view_height); //get height

ViewGroup.LayoutParams params_new=recycler_view.getLayoutParams();
params_new.height=height;
recycler_view.setLayoutParams(params_new);
Run Code Online (Sandbox Code Playgroud)