在RecyclerView.Adapter中使用 ViewBinding 的一個注意點

使用 viewpager2 時遇到如下錯誤, 使用 recyclerview 也有可能會遇到 :

2022-02-10 14:15:43.510 12151-12151/com.sharpcj.demo1 D/sharpcj_tag: onBindViewHolder
...
2022-02-10 14:15:43.548 12151-12151/com.sharpcj.demo1 D/AndroidRuntime: Shutting down VM
2022-02-10 14:15:43.550 12151-12151/com.sharpcj.demo1 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.sharpcj.demo1, PID: 12151
    java.lang.IllegalStateException: Pages must fill the whole ViewPager2 (use match_parent)
    ...

原因在日誌中能看出來,就是 adapter 的 item 必須設置爲 match_parent

例如,我這個 demo 中,使用 viewpager2 實現一個 banner 頁面, item view 只有一個 ImageView 用來展示圖片,我的 banner 頁面高度爲 200dp。我應該將 viewpager2 的高度設置爲 200dp,而 item 佈局文件,高度也要設置爲 match_parent

banner_item_view.xml 文件如下:

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/iv_banner"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
</ImageView>

adpater 部分代碼如下:

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

而如果使用 ViewBinding ,則代碼如下:

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
    val viewBinding = BannerItemViewBinding.inflate(LayoutInflater.from(parent.context))
    val layoutParams = ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.MATCH_PARENT
    )
    viewBinding.root.layoutParams = layoutParams
    return MyViewHolder(viewBinding.root)
}

此時,佈局文件中設置的寬高已經不生效了。

總結:

如果不使用 ViewBinding, 則須在 xml 文件中設置 item view 寬高爲 match_parent
如果使用 ViewBinding, 則需要動態設置 layoutParams, 且寬高設置爲 LayoutParams.MATCH_PARENT

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章