-
Notifications
You must be signed in to change notification settings - Fork 3
/
ExtendedChipGroup.kt
222 lines (204 loc) · 10.3 KB
/
ExtendedChipGroup.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package io.github.tiarait.extendedchipgroup
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.ColorStateList
import android.util.AttributeSet
import android.util.Log
import android.view.View
import androidx.core.view.*
import com.google.android.material.chip.Chip
import com.google.android.material.chip.ChipGroup
class ExtendedChipGroup : ChipGroup {
private val DEF_STYLE_RES = com.google.android.material.R.style.Widget_MaterialComponents_ChipGroup
//макс колво строк - плавающая переменная взависимости скрыто или нет
private var maxRow = Int.MAX_VALUE
//макс колво строк - переменная из xml
var maxRowDef = Int.MAX_VALUE
//имя кнопки ЕЩЕ
private var chipMoreTitle = ""
//имя кнопки СКРЫТЬ
private var chipHideTitle = ""
//цвет кнопки СКРЫТЬ/ЕЩЕ
private var chipMoreColor = -0xeee
private var chipMoreColorPressed = -0xc5c5c5
private var chipMoreColorText = -0x000
private var colorStateList: ColorStateList
//для обновления элементов
private var lastChipsList: ArrayList<String> = ArrayList()
private var mLineSpacing = 0
private var mItemSpacing = 0
private var mChipFixed = false
constructor(context: Context?) : this(context, null)
constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, com.google.android.material.R.attr.chipGroupStyle)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
@SuppressLint("ChipGroup") val a = context!!.obtainStyledAttributes(
attrs,
R.styleable.ChipGroup,
defStyleAttr,
DEF_STYLE_RES)
//получаем maxRow из xml
maxRowDef = a.getColor(R.styleable.ChipGroup_maxRow, maxRow)
if (maxRowDef > 0) isSingleLine = false
//или наоборот, смотря что в приоритете
//if (isSingleLine) maxRowDef = Int.MAX_VALUE
maxRow = maxRowDef
//получаем имя кнопки ЕЩЕ из xml
chipMoreTitle = a.getString(R.styleable.ChipGroup_additionalChipMore).toString()
//получаем имя кнопки СКРЫТЬ из xml
chipHideTitle = a.getString(R.styleable.ChipGroup_additionalChipHide).toString()
//получаем цвет кнопки СКРЫТЬ/ЕЩЕ из xml
chipMoreColor = a.getColor(R.styleable.ChipGroup_additionalChipColor, -0xeee)
chipMoreColorPressed = a.getColor(R.styleable.ChipGroup_additionalChipColorPressed, -0xc5c5c5)
chipMoreColorText = a.getColor(R.styleable.ChipGroup_additionalTextColor, -0x000)
//фиксируем chip в последней макс строке
mChipFixed = a.getBoolean(R.styleable.ChipGroup_additionalChipFixed, false)
colorStateList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_pressed), intArrayOf()),
intArrayOf(
chipMoreColorPressed,
chipMoreColor
)
)
val array = context.theme.obtainStyledAttributes(attrs, R.styleable.FlowLayout, 0, 0)
mLineSpacing = array.getDimensionPixelSize(com.google.android.material.R.styleable.FlowLayout_lineSpacing, 0)
mItemSpacing = array.getDimensionPixelSize(R.styleable.FlowLayout_itemSpacing, 0)
}
fun setMaxRow(max: Int) {
maxRow = max
maxRowDef = max
}
fun setShowText(title: String) {
chipMoreTitle = title
}
fun setHideText(title: String) {
chipHideTitle = title
}
fun update() {
setChips(ArrayList(lastChipsList))
}
//устанавливаем Chip'ы из List<String>, lastChipsList должен быть такого же типа
//List<Chip> - не работает (не обновляются view)
fun setChips(text: List<String>) {
removeAllViews()
lastChipsList.clear()
for (string in text) {
if (string.isNotEmpty()) {
val chip = Chip(context)
chip.text = string
chip.isSelected = true
chip.isCheckable = true
lastChipsList.add(string)
addView(chip)
}
}
}
//в оригинале (FlowLayout) - rowCount
var row = 0
// var prevBackgroundColor: ColorStateList? = null
// var prevTextColor: Int? = null
//копия с оригинала (FlowLayout) + корректировки
override fun onLayout(sizeChanged: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
if (childCount == 0) {
row = 0
return
}
row = 1
val isRtl = ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL
val paddingStart = if (isRtl) paddingRight else paddingLeft
val paddingEnd = if (isRtl) paddingLeft else paddingRight
var childStart = paddingStart
var childTop = paddingTop
var childBottom = childTop
var childEnd: Int
val maxChildEnd = right - left - paddingEnd
for (i in 0 until childCount) {
if (getChildAt(i) != null) {
val child = getChildAt(i) as Chip
// if (prevBackgroundColor == null) prevBackgroundColor = child.chipBackgroundColor
// if (prevTextColor == null) prevTextColor = child.currentTextColor
if (child.visibility == View.GONE) {
child.setTag(R.id.row_index_key, -1)
continue
}
val lp = child.layoutParams
var startMargin = 0
var endMargin = 0
if (lp is MarginLayoutParams) {
startMargin = MarginLayoutParamsCompat.getMarginStart(lp)
endMargin = MarginLayoutParamsCompat.getMarginEnd(lp)
}
childEnd = childStart + startMargin + child.measuredWidth
var pChild: Chip? = null
if (getChildAt(i-1) != null && getChildAt(i-1) is Chip && mChipFixed) {
pChild = getChildAt(i-1) as Chip
}
if (!isSingleLine && (childEnd > maxChildEnd || (pChild != null && pChild.text == chipHideTitle))) {
childStart = paddingStart
childTop = childBottom + mLineSpacing
//если строк больше чем maxRow - заменяем последний элемент пред строки на
//"chipMoreTitle/ЕЩЕ (колво оставшихся)"
if (row == maxRow && (i - 1) > 0 && chipMoreTitle.isNotEmpty()) {
val showChip = (getChildAt(i - 1) as Chip)
showChip.setTextColor(chipMoreColorText)
showChip.chipBackgroundColor = colorStateList
showChip.text = chipMoreTitle + " (${childCount - i + 1})"
showChip.isCheckable = false
showChip.isSelected = false
//при клике на chipMoreTitle выставляем maxRow на максимум и обновляем элементы
//после добавляем chipHideTitle
showChip.setOnClickListener {
maxRow = Int.MAX_VALUE
setChips(ArrayList(lastChipsList))
if (chipHideTitle.isNotEmpty()) {
val hideChip = Chip(context)
hideChip.chipBackgroundColor = colorStateList
hideChip.setTextColor(chipMoreColorText)
hideChip.text = chipHideTitle
hideChip.isSelected = false
hideChip.isCheckable = false
//при клике на chipHideTitle выставляем maxRow на заданный и обновляем элементы
hideChip.setOnClickListener {
maxRow = maxRowDef
setChips(ArrayList(lastChipsList))
}
if (mChipFixed) addView(hideChip, i-1)
else addView(hideChip)
}
}
}
row++
}
//проверяем - если строк больше чем maxRow - скрываем элементы
child.visibility = if (row > maxRow) View.GONE else View.VISIBLE
// if (child.text != chipHideTitle) {
//
// if (prevTextColor != null)
// child.setTextColor(prevTextColor!!)
// if (lastChipsList.size > i)
// child.text = lastChipsList[i]
// if (prevBackgroundColor != null)
// child.chipBackgroundColor = prevBackgroundColor
// child.isCheckable = true
// child.isSelected = true
// child.setOnClickListener {
//
// }
// }
child.setTag(R.id.row_index_key, row - 1)
childEnd = childStart + startMargin + child.measuredWidth
childBottom = childTop + child.measuredHeight
if (isRtl) {
child.layout(
maxChildEnd - childEnd,
childTop,
maxChildEnd - childStart - startMargin,
childBottom
)
} else {
child.layout(childStart + startMargin, childTop, childEnd, childBottom)
}
childStart += startMargin + endMargin + child.measuredWidth + mItemSpacing
}
}
}
}