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

以上代碼親測沒問題,有問題請留言
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/126547.html
標籤:AI
上一篇:Android 影片底部導航欄
下一篇:flutter使用local_auth插件出現local_auth plugin requires activity to be a FragmentActivity.
