Android仿抖音App 列表滑动 PagerSnapHelper

抖音列表滑动,就是用了 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

 

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

 

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值