@@ -9,21 +9,23 @@ import android.widget.LinearLayout
9
9
import androidx.recyclerview.widget.RecyclerView
10
10
import com.bumptech.glide.Glide
11
11
import com.pengxh.kt.lite.R
12
- import com.pengxh.kt.lite.extensions.dp2px
13
- import com.pengxh.kt.lite.extensions.getScreenWidth
14
12
15
13
16
14
/* *
17
15
* 数量可编辑图片适配器
18
16
*
19
- * @param imageCountLimit 最多显示几张图片,每行3张图片
20
- * @param spacing 上下左右外边距,无需在 [androidx.recyclerview.widget.RecyclerView] 设置边距
17
+ * @param context 使用适配的上下文
18
+ * @param viewWidth RecyclerView实际宽度,一般情况下就是屏幕宽度,但是如果有其他控件和它在同一行,需要计算实际宽度,不然无法正确显示RecyclerView item的布局
19
+ * @param imageCountLimit 最多显示的图片数目
20
+ * @param spanCount 每行显示的图片数目
21
21
* */
22
22
class EditableImageAdapter (
23
- private val context : Context , private val imageCountLimit : Int , private val spacing : Int
23
+ private val context : Context ,
24
+ private val viewWidth : Int ,
25
+ private val imageCountLimit : Int ,
26
+ private val spanCount : Int
24
27
) : RecyclerView.Adapter<ViewHolder>() {
25
28
26
- private val screenWidth by lazy { context.getScreenWidth() }
27
29
private var images: MutableList <String > = ArrayList ()
28
30
29
31
fun setupImage (images : MutableList <String >) {
@@ -49,7 +51,10 @@ class EditableImageAdapter(
49
51
50
52
override fun onBindViewHolder (holder : ViewHolder , position : Int ) {
51
53
val imageView = holder.getView<ImageView >(R .id.imageView)
52
- configImageParams(imageView, holder.bindingAdapterPosition)
54
+ val imageSize = viewWidth / spanCount
55
+ val params = LinearLayout .LayoutParams (imageSize, imageSize)
56
+ imageView.layoutParams = params
57
+
53
58
if (position == itemCount - 1 && images.size < imageCountLimit) {
54
59
imageView.setImageResource(R .drawable.ic_add_pic)
55
60
imageView.setOnClickListener { // 添加图片
@@ -68,25 +73,6 @@ class EditableImageAdapter(
68
73
}
69
74
}
70
75
71
- private fun configImageParams (imageView : ImageView , position : Int ) {
72
- val temp = spacing.dp2px(context)
73
- val imageSize = (screenWidth - temp * 3 ) / 3
74
-
75
- val params = LinearLayout .LayoutParams (imageSize, imageSize)
76
- when (position) {
77
- 0 -> params.setMargins(temp, temp, temp shr 1 , temp shr 1 )
78
- 1 -> params.setMargins(temp shr 1 , temp, temp shr 1 , temp shr 1 )
79
- 2 -> params.setMargins(temp shr 1 , temp, temp, temp shr 1 )
80
- 3 -> params.setMargins(temp, temp shr 1 , temp shr 1 , temp shr 1 )
81
- 4 -> params.setMargins(temp shr 1 , temp shr 1 , temp shr 1 , temp shr 1 )
82
- 5 -> params.setMargins(temp shr 1 , temp shr 1 , temp, temp shr 1 )
83
- 6 -> params.setMargins(temp, temp shr 1 , temp shr 1 , temp)
84
- 7 -> params.setMargins(temp shr 1 , temp shr 1 , temp shr 1 , temp)
85
- 8 -> params.setMargins(temp shr 1 , temp shr 1 , temp, temp)
86
- }
87
- imageView.layoutParams = params
88
- }
89
-
90
76
override fun getItemCount (): Int = if (images.size >= imageCountLimit) {
91
77
imageCountLimit
92
78
} else {
0 commit comments