手把手教程,针对初学者(老家伙请跳过),先看效果,能用得上的再继续往下看……
针对上图重叠头像的展示实现方式,最简单的就是使用RecyclerView,利用其装饰器。平常使用RecyclerView都是每个item之间有间距,而这里不仅没间距还重叠了一部分,其实本质上也可以看成是有间距,只不过间距是负值。
直接上代码吧~
布局文件:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http:///apk/res/android"
xmlns:app="http:///apk/res-auto"
xmlns:tools="http:///tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!--前面的心形和后面的11人喜欢,不是本文重点,略略略-->
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Activity代码:MainActivity
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val avatarAdapter by lazy { AvatarAdapter() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
//layoutManager设置为线性,方向为横向
binding.recyclerView.layoutManager = LinearLayoutManager(this).apply {
orientation = LinearLayoutManager.HORIZONTAL
}
//设置adapter
binding.recyclerView.adapter = avatarAdapter
//设置装饰器
binding.recyclerView.addItemDecoration(object : RecyclerView.ItemDecoration() {
override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State
) {
super.getItemOffsets(outRect, view, parent, state)
if (parent.getChildLayoutPosition(view) == 0) { //第一个不偏移
outRect.left = 0
} else { //后面的往左偏移5dp
outRect.left = ConvertUtils.dp2px(-5f) //工具类:将dp转为px
}
}
})
}
}
AvatarAdapter的代码就略了,以及其设置数据源,都很简单。重点只有一个:recyclerView.addItemDecoration()
当然上面的效果也可以用自定义view实现,方法有很多种,自己用的顺手就行。
OK 结束