欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android仿抖音App 列表滑动 PagerSnapHelper

程序员文章站 2022-04-11 15:33:57
...

抖音列表滑动,就是用了 PagerSnapHelper ,PagerSnapHelper 是Android 提供的一个Api,每滑动一个Item,其作用类似于ViewPage那样,直接与RecycleView相关连即可

 

class RecycleActivity : AppCompatActivity() {

    companion object {
        fun launch(context: Context) {
            context.startActivity<RecycleActivity>()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_recycle)
        recycle_view.layoutManager = LinearLayoutManager(this)
        PagerSnapHelper().attachToRecyclerView(recycle_view)
        recycle_view.adapter = MyAdapter()
    }


    class MyAdapter : RecyclerView.Adapter<MyViewHole>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHole {
            val view =
                LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
            return MyViewHole(view)
        }

        override fun getItemCount() = 30

        override fun onBindViewHolder(holder: MyViewHole, position: Int) {
            holder.bind(position)
        }
    }


    class MyViewHole(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bind(position: Int) {
            itemView.findViewById<TextView>(R.id.tv).text = "$position"
        }
    }

}

 

对应的 layout 文件 xml ,注意 item的 宽高是 全屏

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <android.support.v7.widget.AppCompatTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv"
        android:textSize="40sp"
        android:background="@color/color_00a3f3_50"
        android:padding="20dp"
        android:textColor="@color/color_0d0d0d"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent">
    </android.support.v7.widget.AppCompatTextView>

    <View
        android:layout_width="0dp"
        android:layout_height="10dp"
        android:background="@color/color_00a3f3"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent">
    </View>
</android.support.constraint.ConstraintLayout>

 

看下gif

Android仿抖音App 列表滑动 PagerSnapHelper

 

以上代码亲测没问题,有问题请留言

 

 

相关标签: 仿抖音 android