-
Notifications
You must be signed in to change notification settings - Fork 55
/
TextViewExtensions.kt
463 lines (415 loc) · 16.3 KB
/
TextViewExtensions.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
package com.aesean.activitystack.demo.textview
import android.text.Layout
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.ColorRes
import androidx.core.content.res.ResourcesCompat
import androidx.transition.AutoTransition
import androidx.transition.Transition
import androidx.transition.TransitionListenerAdapter
import androidx.transition.TransitionManager
import com.aesean.activitystack.BuildConfig
private const val logTag = "TextViewLayout"
private val enableDebugLog = BuildConfig.DEBUG
private fun log(any: Any?) {
if (enableDebugLog) {
Log.d(logTag, any.toString())
}
}
/**
* TextViewBuilder
* ellipsize textView with custom suffix.
*/
class TextViewSuffixWrapper(val textView: TextView) {
private data class SuffixColor(val fromIndex: Int, val toIndex: Int, val color: Int?, val listener: View.OnClickListener? = null)
var mainContent: CharSequence = textView.text
set(value) {
collapseCache = null
field = value
}
var suffix: CharSequence? = null
set(value) {
collapseCache = null
field = value
}
private var collapseCache: CharSequence? = null
private var collapseLayoutCache: Layout? = null
var isCollapsed: Boolean = false
private set
var enableCache = false
var enableMaxLinesCheck = true
var targetLineCount: Int = 2
var transition: Transition? = AutoTransition()
var sceneRoot: ViewGroup = textView.parent as ViewGroup
private val textWrapper: (text: String, suffix: CharSequence, suffixIndex: Int) -> CharSequence =
{ text, suffix, suffixIndex ->
SpannableStringBuilder(text).apply {
suffixColorList.forEach {
val start = suffixIndex + it.fromIndex
val end = suffixIndex + it.toIndex
it.listener?.also { listener ->
setSpan(object : ClickableSpan() {
override fun onClick(widget: View) {
listener.onClick(widget)
}
}, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
textView.movementMethod = LinkMovementMethod.getInstance()
}
it.color?.also { color ->
setSpan(ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
}
}
private val suffixColorList by lazy {
mutableListOf<SuffixColor>()
}
init {
if (textView.layoutParams.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
throw RuntimeException("textView's width can't be wrap_content. Only support match_parent or specified size")
}
}
fun suffixColor(fromIndex: Int, toIndex: Int, @ColorRes colorRes: Int) {
val color = ResourcesCompat.getColor(textView.resources, colorRes, textView.context.theme)
suffixColorList.add(SuffixColor(fromIndex, toIndex, color, null))
}
fun suffixColor(fromIndex: Int, toIndex: Int, listener: View.OnClickListener) {
suffixColorList.add(SuffixColor(fromIndex, toIndex, null, listener))
}
fun suffixColor(fromIndex: Int, toIndex: Int, @ColorRes colorRes: Int, listener: View.OnClickListener) {
val color = ResourcesCompat.getColor(textView.resources, colorRes, textView.context.theme)
suffixColorList.add(SuffixColor(fromIndex, toIndex, color, listener))
}
@JvmOverloads
fun collapse(animation: Boolean = true) {
performCollapse(
if (animation) {
transition
} else {
null
}
)
}
@JvmOverloads
fun toggle(animation: Boolean = true) {
if (isCollapsed) {
expand(animation)
} else {
collapse(animation)
}
}
@JvmOverloads
fun expand(animation: Boolean = true) {
performExpand(
if (animation) {
this.transition
} else {
null
}
)
}
private fun performExpand(transition: Transition?) {
isCollapsed = false
textView.expand(mainContent = mainContent, transition = transition, sceneRoot = sceneRoot)
}
private fun performCollapse(transition: Transition?) {
require(!(enableMaxLinesCheck && textView.maxLines < targetLineCount)) {
"textView.maxLines(${textView.maxLines}) < targetLineCount($targetLineCount)"
}
isCollapsed = true
fun defaultCollapse() {
textView.maxLines = targetLineCount
textView.ellipsize = TextUtils.TruncateAt.END
val originText = textView.text
textView.text = mainContent
if (transition != null) {
textView.apply {
val layout = this.layout
if (layout != null) {
val targetHeight = layout.height + paddingTop + paddingBottom
text = originText
maxLines = Int.MAX_VALUE
layoutParams.height = targetHeight
layoutParams = layoutParams
transition.addListener(object : TransitionListenerAdapter() {
override fun onTransitionEnd(transition: Transition) {
transition.removeListener(this)
layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
layoutParams = layoutParams
maxLines = targetLineCount
text = mainContent
}
override fun onTransitionCancel(transition: Transition) {
transition.removeListener(this)
}
})
}
TransitionManager.beginDelayedTransition(sceneRoot, transition)
}
}
}
if (suffix == null) {
defaultCollapse()
} else {
if (enableCache && collapseCache != null && collapseLayoutCache == textView.layout) {
if (collapseCache == mainContent) {
return
}
if (transition != null) {
textView.setTextWithAnimator(content = collapseCache!!, transition = transition, sceneRoot = sceneRoot)
} else {
textView.maxLines = targetLineCount
textView.ellipsize = TextUtils.TruncateAt.END
textView.text = collapseCache
}
} else {
textView.collapse(
mainContent = mainContent,
suffix = suffix!!,
targetLineCount = targetLineCount,
transition = transition,
sceneRoot = sceneRoot,
onSuccess = { text ->
collapseCache = text
collapseLayoutCache = textView.layout
},
onFailed = {
defaultCollapse()
},
textWrapper = textWrapper
)
}
}
}
}
@JvmOverloads
fun TextView.setTextWithAnimator(
content: CharSequence,
transition: Transition = AutoTransition(),
sceneRoot: ViewGroup = this.parent as ViewGroup
) {
val originText = this.text
this.text = content
val layout = this.layout
if (layout != null) {
val targetHeight = layout.height + paddingTop + paddingBottom
text = originText
layoutParams.height = targetHeight
layoutParams = layoutParams
transition.addListener(object : TransitionListenerAdapter() {
override fun onTransitionEnd(transition: Transition) {
transition.removeListener(this)
layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
layoutParams = layoutParams
text = content
}
override fun onTransitionCancel(transition: Transition) {
transition.removeListener(this)
}
})
}
TransitionManager.beginDelayedTransition(sceneRoot, transition)
}
/**
* collapse TextView
* @param mainContent text
* @param suffix suffix
* @param targetLineCount targetLineCount
* @param transition for animation. If is null, there will be no animation and it will take effect immediately.
* @param onSuccess There may be asynchronous operations here, You can listen to the end event via onSuccess.
* @param textWrapper You can wrap the text, such as changing the color through a SpannableString.
*/
fun TextView.collapse(
mainContent: CharSequence,
suffix: CharSequence,
targetLineCount: Int,
transition: Transition? = AutoTransition(),
sceneRoot: ViewGroup = this.parent as ViewGroup,
onSuccess: ((text: CharSequence) -> Unit)? = null,
onFailed: ((text: CharSequence) -> Unit)? = null,
textWrapper: ((text: String, suffix: CharSequence, suffixIndex: Int) -> CharSequence)?
) {
val originText = text
setTextWithSuffix(
mainContent = mainContent, suffix = suffix, targetLineCount = targetLineCount,
onSuccess = { result ->
if (transition == null) {
onSuccess?.invoke(result)
} else {
val targetText = text
val targetHeight = layout.height + paddingTop + paddingBottom
text = originText
layoutParams.height = targetHeight
layoutParams = layoutParams
transition.addListener(object : TransitionListenerAdapter() {
override fun onTransitionEnd(transition: Transition) {
transition.removeListener(this)
layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
layoutParams = layoutParams
text = targetText
onSuccess?.invoke(result)
}
override fun onTransitionCancel(transition: Transition) {
transition.removeListener(this)
}
})
TransitionManager.beginDelayedTransition(sceneRoot, transition)
}
},
onFailed = {
this.text = mainContent
this.maxLines = targetLineCount
onFailed?.invoke(mainContent)
},
textWrapper = textWrapper
)
}
/**
* expand TextView
* @param mainContent text
* @param transition for animation. If is null, there will be no animation and it will take effect immediately.
*/
fun TextView.expand(
mainContent: CharSequence, transition: Transition? = AutoTransition(),
sceneRoot: ViewGroup = this.parent as ViewGroup
) {
this.maxLines = Int.MAX_VALUE
this.text = mainContent
transition?.also {
TransitionManager.beginDelayedTransition(sceneRoot, it)
}
}
fun TextView.setTextWithSuffix(
mainContent: CharSequence,
suffix: CharSequence,
targetLineCount: Int,
onSuccess: (text: CharSequence) -> Unit = {},
onFailed: (text: CharSequence) -> Unit = { text ->
this.text = text
maxLines = targetLineCount
ellipsize = TextUtils.TruncateAt.END
},
textWrapper: ((text: String, suffix: CharSequence, suffixIndex: Int) -> CharSequence)?
) {
val originText = text
fun autoSet(index: Int) {
if (index < 0) {
onFailed(originText)
} else {
text = if (index >= mainContent.length) {
mainContent
} else {
val msg = "${mainContent.substring(0, index)}$suffix"
textWrapper?.invoke(msg, suffix, index) ?: msg
}
onSuccess(text)
}
}
if (layout == null) {
val listener = object : View.OnLayoutChangeListener {
override fun onLayoutChange(
v: View?,
left: Int, top: Int, right: Int, bottom: Int,
oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int
) {
removeOnLayoutChangeListener(this)
if (layout == null) {
onFailed(text)
} else {
post {
val start = System.currentTimeMillis()
autoSet(binarySearch(mainContent, suffix, targetLineCount, textWrapper))
val end = System.currentTimeMillis()
log(">>>>>performance: ${end - start}ms")
}
}
}
}
addOnLayoutChangeListener(listener)
requestLayout()
} else {
val start = System.currentTimeMillis()
autoSet(binarySearch(mainContent, suffix, targetLineCount, textWrapper))
val end = System.currentTimeMillis()
log(">>>>>performance: ${end - start}ms")
}
}
/**
* Note: binary search will change the text, so be sure to remember the case where the search failed.
*/
private fun TextView.binarySearch(
mainContent: CharSequence,
suffix: CharSequence,
targetLineCount: Int,
textWrapper: ((text: String, suffix: CharSequence, suffixIndex: Int) -> CharSequence)?
): Int {
var verifyCount = 0
val verifyCache = mutableMapOf<Int, Int>()
fun verify(start: Int, end: Int): Int {
val key = (start shl 16) or end
val hit = verifyCache[key]
if (hit != null) {
log("verify: $end cached")
return hit
}
verifyCount++
val tmp = mainContent.substring(start, end)
val context = "$tmp$suffix"
text = textWrapper?.invoke(context, suffix, end) ?: context
val lineCount = this.lineCount
log("verify: $end, lineCount = $lineCount")
verifyCache[key] = lineCount
return lineCount
}
if (layout == null) {
log("layout is null")
return -1
}
val verify = verify(0, mainContent.length)
if (verify <= targetLineCount) {
log("verify <= targetLineCount, verify = $verify, targetLineCount = $targetLineCount")
text = mainContent
return mainContent.length
}
// Remove optimization. Some special characters will cause bug.
// var left = this.layout.getLineEnd(targetLineCount - 2)
// var right = this.layout.getLineEnd(targetLineCount - 1)
var left = 0
var right = mainContent.length
log("left = $left, right = $right")
while (left <= right) {
val mid = (left + right) / 2
val pLineCount = verify(0, mid)
var s = "binarySearch: ($left, $mid, $right), pLineCount = $pLineCount"
if (pLineCount < targetLineCount) {
s += ", targetLineCount = $targetLineCount, pLineCount < targetLineCount"
left = mid + 1
} else if (pLineCount == targetLineCount) {
val nLineCount = verify(0, mid + 1)
s += ", nLineCount = $nLineCount"
if (nLineCount < targetLineCount + 1) {
left = mid + 1
} else if (nLineCount == targetLineCount + 1) {
log("success = $mid, verifyCount = $verifyCount")
return mid
} else {
// error impossible
log("impossible")
break
}
} else {
right = mid - 1
}
log("$s, text = ${mainContent.substring(0, mid) + suffix}")
}
log("failed, verifyCount = $verifyCount")
return -1
}