美文网首页Android开发经验谈
Grid形式的RecyclerView屏幕宽度自适应

Grid形式的RecyclerView屏幕宽度自适应

作者: 纵马横刀pro | 来源:发表于2020-10-12 22:12 被阅读0次

    RecyclerView以Grid形式展示时,有时候的需求是是指定一行的item数量后,要求每个item能平均的撑满扣处间距margin后的剩余空间。
    此时,为了适配不同分辨率屏幕,不能把Item的width写死,否则在屏幕大的手机上,会导致列表两边空白太多,在屏幕小的手机上,会导致右边显示不完整。
    这种需求下的最佳实践是让RecyclerViewwidth和Item的width都为match_parent,在Item内部设置宽高比。然后在RecyclerView设置padding控制左右两边边距,在Item内部设置layout_margin控制item之间的边距。

    注意:如果RecyclerViewwidth不为match_parent则Item的width设置match_parent无效,还是wrap_content的效果。

    RecyclerView:

    <android.support.v7.widget.RecyclerView
        android:id="@+id/list_members"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        android:paddingLeft="10dp"
        android:paddingTop="16dp"
        android:paddingRight="10dp"
        android:paddingBottom="16dp"></android.support.v7.widget.RecyclerView>
    

    Item:

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingTop="5dp"
        android:paddingRight="10dp"
        android:paddingBottom="5dp">
        <com.facebook.drawee.view.SimpleDraweeView
            android:id="@+id/avatar"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:actualImageScaleType="fitCenter"
            app:layout_constraintBottom_toTopOf="@+id/name"
            app:layout_constraintDimensionRatio="1"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:placeholderImage="@mipmap/ic_avatar_placeholder"
            app:placeholderImageScaleType="fitCenter"
            app:roundAsCircle="true"
            app:viewAspectRatio="1" />
        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="6dp"
            android:alpha="0.7"
            android:ellipsize="end"
            android:maxLines="1"
            android:textColor="@color/textDark"
            android:textSize="12sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/avatar" />
    </android.support.constraint.ConstraintLayout>
    
    image.png

    相关文章

      网友评论

        本文标题:Grid形式的RecyclerView屏幕宽度自适应

        本文链接:https://www.haomeiwen.com/subject/vkalpktx.html