-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathViewExtensions.kt
354 lines (302 loc) · 12 KB
/
ViewExtensions.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
package co.temy.android.ktx
import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.text.method.LinkMovementMethod
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.AutoCompleteTextView
import android.widget.CheckBox
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.text.toSpannable
import androidx.core.view.ViewCompat
import androidx.core.view.children
import androidx.core.view.doOnPreDraw
import androidx.core.widget.TextViewCompat
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.snackbar.Snackbar
fun EditText.value() = text.toString()
inline fun EditText.setOnEditorActionListener(crossinline onAction: (Int) -> Boolean) {
setOnEditorActionListener { _, actionId, _ -> onAction(actionId) }
}
inline fun EditText.setOnDoneEditorActionListener(crossinline onAction: (Int) -> Unit = {}) {
setOnEditorActionListener { actionId ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
onAction(actionId)
true
} else false
}
}
/**
* Runs [onAction] block and hides a keyboard when [EditorInfo.IME_ACTION_DONE] is fired.
*
* @param onAction function to be called when [[EditorInfo.IME_ACTION_DONE] is fired
*/
inline fun EditText.setHideKeyboardEditorActionListener(crossinline onAction: (Int) -> Unit = {}) {
setOnDoneEditorActionListener {
hideKeyboard()
onAction(it)
}
}
fun View.showKeyboard() {
val imm: InputMethodManager? = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
imm?.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
}
fun View.hideKeyboard() {
val imm: InputMethodManager? = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
imm?.hideSoftInputFromWindow(windowToken, 0)
this.clearFocus()
}
/**
* @return [View.VISIBLE] if Boolean value is true, [View.GONE] otherwise.
*/
fun Boolean.asVisibleOrGoneFlag() = if (this) View.VISIBLE else View.GONE
/**
* @return [View.GONE] if Boolean value is true, [View.VISIBLE] otherwise.
*/
fun Boolean.asGoneOrVisibleFlag() = if (this) View.GONE else View.VISIBLE
/**
* @return [View.VISIBLE] if Boolean value is true, [View.INVISIBLE] otherwise.
*/
fun Boolean.asVisibleOrInvisibleFlag() = if (this) View.VISIBLE else View.INVISIBLE
/**
* Resets nested vertical scroll position.
*
* Can be used to reset [CoordinatorLayout]'s behaviours that depends on scrolling views.
*/
fun RecyclerView.resetNestedVerticalScroll() {
startNestedScroll(androidx.core.view.ViewCompat.SCROLL_AXIS_VERTICAL)
dispatchNestedPreScroll(0, -java.lang.Integer.MAX_VALUE, null, null)
dispatchNestedScroll(0, -java.lang.Integer.MAX_VALUE, 0, 0, null)
stopNestedScroll()
}
fun LinearLayoutManager.getCurrentPosition(midScreenX: Int, midScreenY: Int): Int = when(this.orientation) {
LinearLayoutManager.HORIZONTAL -> getCurrentPositionForHorizontalOrientation(midScreenX)
LinearLayoutManager.VERTICAL -> getCurrentPositionForVerticalOrientation(midScreenY)
else -> RecyclerView.NO_POSITION
}
/**
* Get current position for [LinearLayoutManager.HORIZONTAL]
*
* @return position of center item if it exists else
* @return first completely visible or first visible item position
*
* @return [RecyclerView.NO_POSITION] if [LinearLayoutManager] doesn't have horizontal orientation
*/
private fun LinearLayoutManager.getCurrentPositionForHorizontalOrientation(midScreenX: Int) : Int {
if (this.orientation == LinearLayoutManager.HORIZONTAL) {
val centerPosition = getCenterPositionForHorizontalOrientation(midScreenX)
return if (centerPosition == RecyclerView.NO_POSITION) {
getCompletelyVisibleOrFirstPosition()
} else centerPosition
}
return RecyclerView.NO_POSITION
}
private fun LinearLayoutManager.getCompletelyVisibleOrFirstPosition(): Int {
val firstCompletelyVisiblePosition = findFirstCompletelyVisibleItemPosition()
return if (firstCompletelyVisiblePosition == RecyclerView.NO_POSITION) {
findFirstVisibleItemPosition()
} else {
firstCompletelyVisiblePosition
}
}
/**
* Get position of center item for [LinearLayoutManager.HORIZONTAL]
*
* @return position of item with start X less than middle of the screen and end X more than middle of the screen
*
* @return [RecyclerView.NO_POSITION] if [LinearLayoutManager] doesn't have horizontal orientation or there is no item that meets requirements
*/
private fun LinearLayoutManager.getCenterPositionForHorizontalOrientation(midScreenX: Int) : Int {
if (this.orientation == LinearLayoutManager.HORIZONTAL) {
val firstPosition = this.findFirstVisibleItemPosition()
val lastPosition = this.findLastVisibleItemPosition()
for (position in firstPosition..lastPosition) {
val view = this.findViewByPosition(position)
if (view != null) {
val viewWidth = view.measuredWidth
val viewStartX = view.x
val viewEndX = viewStartX + viewWidth
if (viewStartX < midScreenX && viewEndX > midScreenX) {
return position
}
}
}
return RecyclerView.NO_POSITION
}
return RecyclerView.NO_POSITION
}
/**
* Get current position for [LinearLayoutManager.VERTICAL]
*
* @return position of center item if it exists else
* @return first completely visible or first visible item position
*
* @return [RecyclerView.NO_POSITION] if [LinearLayoutManager] doesn't have vertical orientation
*/
private fun LinearLayoutManager.getCurrentPositionForVerticalOrientation(midScreenY: Int): Int {
if (this.orientation == LinearLayoutManager.VERTICAL) {
val centerPosition = getCenterPositionForVerticalOrientation(midScreenY)
return if (centerPosition == RecyclerView.NO_POSITION) {
getCompletelyVisibleOrFirstPosition()
} else centerPosition
}
return RecyclerView.NO_POSITION
}
/**
* Get position of center item for [LinearLayoutManager.VERTICAL]
*
* @return position of item with start Y less than middle of the screen and end Y more than middle of the screen
*
* @return [RecyclerView.NO_POSITION] if [LinearLayoutManager] doesn't have vertical orientation or there is no item that meets requirements
*/
private fun LinearLayoutManager.getCenterPositionForVerticalOrientation(midScreenY: Int) : Int {
if (this.orientation == LinearLayoutManager.VERTICAL) {
val firstPosition = this.findFirstVisibleItemPosition()
val lastPosition = this.findLastVisibleItemPosition()
for (position in firstPosition..lastPosition) {
val view = this.findViewByPosition(position)
if (view != null) {
val viewHeight = view.measuredHeight
val viewStartY = view.y
val viewEndY= viewStartY + viewHeight
if (viewStartY < midScreenY && viewEndY > midScreenY) {
return position
}
}
}
return RecyclerView.NO_POSITION
}
return RecyclerView.NO_POSITION
}
fun View.setBottomPadding(bottomPadding: Int) {
setPadding(paddingLeft, paddingTop, paddingRight, bottomPadding)
}
/**
* Triggers when recycler view state changes to [RecyclerView.SCROLL_STATE_IDLE].
*/
inline fun RecyclerView.addOnIdleStateListener(crossinline listener: (RecyclerView) -> Unit) {
addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
listener.invoke(recyclerView)
}
}
})
}
fun View.setProportionalHeight(imageWidth: Float, imageHeight: Float) {
doOnPreDraw {
val maxWidth = it.width.toFloat()
it.layoutParams = it.layoutParams.calculateProportionalHeight(maxWidth, imageWidth, imageHeight)
}
}
fun View.setProportionalAspectRatio(imageWidth: Float, imageHeight: Float) {
doOnPreDraw {
val maxWidth = it.width.toFloat()
val maxHeight = it.height.toFloat()
it.layoutParams = it.layoutParams.calculateAspectRatio(maxWidth, maxHeight, imageWidth, imageHeight)
}
}
fun View.setElevationCompat(value: Float) {
ViewCompat.setElevation(this, value)
}
fun View.getElevationCompat() = ViewCompat.getElevation(this)
fun View.enableChildrenViews(enable: Boolean) {
this.isEnabled = enable
if (this is ViewGroup) {
this.children.forEach { it.enableChildrenViews(enable) }
}
}
/**
* Attaches Live data to Edit Text.
* This will update Live Data data with all text changes from Edit Text.
*/
fun <T> AutoCompleteTextView.attachLiveData(data: MutableLiveData<T>) {
setOnItemClickListener { parent, view, position, id ->
data.value = parent.adapter.getItem(position) as T
}
}
/**
* Attaches Live data to Edit Text.
* This will update Live Data data with all text changes from Edit Text.
*/
fun EditText.attachLiveData(data: MutableLiveData<String>) {
data.value = text.toString()
addTextChangedListener {
data.value = it.toString()
}
}
/**
* Attaches Live data to Check Box.
* This will update Live Data data with all state changes from Check Box.
*/
fun CheckBox.attachLiveData(data: MutableLiveData<Boolean>) {
data.value = isChecked
setOnCheckedChangeListener { _, isChecked ->
data.value = isChecked
}
}
inline fun EditText.addTextChangedListener(crossinline onTextChanged: (text: CharSequence?) -> Unit) {
addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(p0: Editable?) {
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
onTextChanged.invoke(p0)
}
})
}
fun TextView.setTextAppearanceCompat(appearanceId: Int) {
TextViewCompat.setTextAppearance(this, appearanceId)
}
fun Window.disableScreenshots() {
this.setFlags(
WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE
)
}
fun Snackbar.centerMessage(): Snackbar = apply {
val textView = this.view.findViewById<AppCompatTextView>(com.google.android.material.R.id.snackbar_text)
textView.textAlignment = android.view.View.TEXT_ALIGNMENT_CENTER
}
fun Snackbar.show(isCentered: Boolean) {
if (isCentered) {
this.centerMessage()
}
this.show()
}
/**
* Searches for [clickableText] inside the TextView's text property.
* If found, highlights [clickableText] with [clickableTextColor] and sets [clickListener] to it.
*
* @param clickableText text that must be present inside TextView's text property
* @param clickableTextColor color for highlighting [clickableText]
* @param clickListener functions that will we invoked on [clickableText] click
*/
fun TextView.makeTextClickable(clickableText: String, clickableTextColor: Int, clickListener: () -> (Unit)) {
this.movementMethod = LinkMovementMethod.getInstance()
this.text = this.text.toString().makeTextClickable(clickableText, clickableTextColor, clickListener)
}
fun TextView.makeSpannableTextClickable(clickableText: String, clickableTextColor: Int, clickListener: () -> (Unit)) {
this.movementMethod = LinkMovementMethod.getInstance()
this.text = this.text.toSpannable().makeTextClickable(clickableText, clickableTextColor, clickListener)
}
fun View.removeFocus() {
clearFocus()
isFocusable = false
isFocusableInTouchMode = false
}
fun View.setFocus() {
isFocusable = true
isFocusableInTouchMode = true
}
fun Boolean.asTextOrNullInputType() = if (this) EditorInfo.TYPE_CLASS_TEXT else EditorInfo.TYPE_NULL