Android imitation Douyin App list sliding PagerSnapHelper

TikTok list sliding is to use PagerSnapHelper. PagerSnapHelper is an API provided by Android. Every time you slide an Item, its function is similar to that of ViewPage, and it can be directly connected to 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"
        }
    }

}

 

The corresponding layout file xml, note that the width and height of the item is full screen

<?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>

 

Look at the gif

 

There is no problem with the above code, please leave a message if you have any questions

 

 

Guess you like

Origin blog.csdn.net/Leo_Liang_jie/article/details/108753800