Android 使用RecycleView制作头像堆叠效果

效果如下:
Android 使用RecycleView制作头像堆叠效果_第1张图片
代码如下:
这里给出部分关键代码
逻辑代码:

//反方向排列
  recycleView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true).apply {
            stackFromEnd = true
        }

adapter:

/**
 * 层叠头像Adapter
 */
class LayerAvatarAdapter(): RecycleBaseAdapter<LayerAvatarViewHolder>() {
    var avatarList = arrayListOf<String>()
        set(value) {
            field = value
            notifyDataSetChanged()
        }
    override fun getItemCount() =  if (avatarList.size > 3) 3 else avatarList.size

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LayerAvatarViewHolder {
        super.onCreateViewHolder(parent, viewType)
        val view = inflater.inflate(R.layout.item_layer_avatar,parent,false);
        return LayerAvatarViewHolder(view)
    }

    override fun onBindViewHolder(holder: LayerAvatarViewHolder, position: Int) {
        super.onBindViewHolder(holder, position)
        if(position == avatarList.size - 1){
            setMargins(holder.root,0,0,0,0)
        }
        GlideUtils.loadCircle(context,avatarList[position],holder.avatar)
    }
    private fun setMargins(v: View, l: Int, t: Int, r: Int, b: Int) {
        if (v.layoutParams is ViewGroup.MarginLayoutParams) {
            val p = v.layoutParams as ViewGroup.MarginLayoutParams
            p.setMargins(l, t, r, b)
//            v.layoutParams = p
            v.requestLayout()
        }
    }
}

LayerAvatarViewHolder

/**
 * 层叠头像
 */
class LayerAvatarViewHolder(@NonNull itemView : View) : RecycleBaseViewHolder(itemView) {
    val avatar: ImageView = itemView.findViewById(R.id.item_layer_avatar)
    val root: View = itemView.findViewById(R.id.root)
}

xml


<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="-5dp">
    <ImageView
        android:id="@+id/item_layer_avatar"
        android:layout_width="@dimen/dp_20"
        android:layout_height="@dimen/dp_20"/>
LinearLayout>

你可能感兴趣的:(Android)