aboutsummaryrefslogtreecommitdiff
path: root/core/src/main/kotlin/ca/allanwang/kau/utils/ViewUtils.kt
blob: 4e020bcb9f20555577b4441b0e443cfe43ecc106 (plain)
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
@file:Suppress("NOTHING_TO_INLINE")

package ca.allanwang.kau.utils

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.support.annotation.ColorInt
import android.support.annotation.ColorRes
import android.support.annotation.RequiresApi
import android.support.annotation.StringRes
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.support.design.widget.TextInputEditText
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import ca.allanwang.kau.ui.createSimpleRippleDrawable
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.IIcon


/**
 * Created by Allan Wang on 2017-05-31.
 */

@KauUtils
inline fun <T : View> T.visible(): T {
    visibility = View.VISIBLE
    return this
}

@KauUtils
inline fun <T : View> T.invisible(): T {
    visibility = View.INVISIBLE
    return this
}

@KauUtils
inline fun <T : View> T.gone(): T {
    visibility = View.GONE
    return this
}

@KauUtils
inline fun <T : View> T.invisibleIf(invisible: Boolean): T = if (invisible) invisible() else visible()

@KauUtils
inline fun <T : View> T.visibleIf(visible: Boolean): T = if (visible) visible() else gone()

@KauUtils
inline fun <T : View> T.goneIf(gone: Boolean): T = visibleIf(!gone)

@KauUtils
inline val View.isVisible: Boolean
    get() = visibility == View.VISIBLE

@KauUtils
inline val View.isInvisible: Boolean
    get() = visibility == View.INVISIBLE

@KauUtils
inline val View.isGone: Boolean
    get() = visibility == View.GONE

@KauUtils
inline fun View.setBackgroundColorRes(@ColorRes color: Int) = setBackgroundColor(context.color(color))

fun View.snackbar(text: String, duration: Int = Snackbar.LENGTH_LONG, builder: Snackbar.() -> Unit = {}): Snackbar {
    val snackbar = Snackbar.make(this, text, duration)
    snackbar.builder()
    snackbar.show()
    return snackbar
}

fun View.snackbar(@StringRes textId: Int, duration: Int = Snackbar.LENGTH_LONG, builder: Snackbar.() -> Unit = {}) = snackbar(context.string(textId), duration, builder)

@KauUtils
fun ImageView.setIcon(icon: IIcon?, sizeDp: Int = 24, @ColorInt color: Int = Color.WHITE, builder: IconicsDrawable.() -> Unit = {}) {
    if (icon == null) return
    setImageDrawable(icon.toDrawable(context, sizeDp = sizeDp, color = color, builder = builder))
}

@KauUtils
inline val FloatingActionButton.isHidden
    get() = !isShown

fun FloatingActionButton.showIf(show: Boolean) = if (show) show() else hide()

fun FloatingActionButton.hideIf(hide: Boolean) = if (hide) hide() else show()

@KauUtils
fun ViewGroup.inflate(layoutId: Int, attachToRoot: Boolean = false): View = LayoutInflater.from(context).inflate(layoutId, this, attachToRoot)

/**
 * Set left margin to a value in px
 */
@KauUtils
fun View.setMarginLeft(margin: Int) = setMargins(margin, KAU_LEFT)

/**
 * Set top margin to a value in px
 */
@KauUtils
fun View.setMarginTop(margin: Int) = setMargins(margin, KAU_TOP)

/**
 * Set right margin to a value in px
 */
@KauUtils
fun View.setMarginRight(margin: Int) = setMargins(margin, KAU_RIGHT)

/**
 * Set bottom margin to a value in px
 */
@KauUtils
fun View.setMarginBottom(margin: Int) = setMargins(margin, KAU_BOTTOM)

/**
 * Set left and right margins to a value in px
 */
@KauUtils
fun View.setMarginHorizontal(margin: Int) = setMargins(margin, KAU_HORIZONTAL)

/**
 * Set top and bottom margins to a value in px
 */
@KauUtils
fun View.setMarginVertical(margin: Int) = setMargins(margin, KAU_VERTICAL)

/**
 * Set all margins to a value in px
 */
@KauUtils
fun View.setMargin(margin: Int) = setMargins(margin, KAU_ALL)

/**
 * Base margin setter
 * returns true if setting is successful, false otherwise
 */
@KauUtils
private fun View.setMargins(margin: Int, flag: Int): Boolean {
    val p = (layoutParams as? ViewGroup.MarginLayoutParams) ?: return false
    p.setMargins(
            if (flag and KAU_LEFT > 0) margin else p.leftMargin,
            if (flag and KAU_TOP > 0) margin else p.topMargin,
            if (flag and KAU_RIGHT > 0) margin else p.rightMargin,
            if (flag and KAU_BOTTOM > 0) margin else p.bottomMargin
    )
    return true
}

/**
 * Set left padding to a value in px
 */
@KauUtils
fun View.setPaddingLeft(padding: Int) = setPadding(padding, KAU_LEFT)

/**
 * Set top padding to a value in px
 */
@KauUtils
fun View.setPaddingTop(padding: Int) = setPadding(padding, KAU_TOP)

/**
 * Set right padding to a value in px
 */
@KauUtils
fun View.setPaddingRight(padding: Int) = setPadding(padding, KAU_RIGHT)

/**
 * Set bottom padding to a value in px
 */
@KauUtils
fun View.setPaddingBottom(padding: Int) = setPadding(padding, KAU_BOTTOM)

/**
 * Set left and right padding to a value in px
 */
@KauUtils
fun View.setPaddingHorizontal(padding: Int) = setPadding(padding, KAU_HORIZONTAL)

/**
 * Set top and bottom padding to a value in px
 */
@KauUtils
fun View.setPaddingVertical(padding: Int) = setPadding(padding, KAU_VERTICAL)

/**
 * Set all padding to a value in px
 */
@KauUtils
fun View.setPadding(padding: Int) = setPadding(padding, KAU_ALL)

/**
 * Base padding setter
 */
@KauUtils
private fun View.setPadding(padding: Int, flag: Int) {
    setPadding(
            if (flag and KAU_LEFT > 0) padding else paddingLeft,
            if (flag and KAU_TOP > 0) padding else paddingTop,
            if (flag and KAU_RIGHT > 0) padding else paddingRight,
            if (flag and KAU_BOTTOM > 0) padding else paddingBottom
    )
}

@KauUtils
fun View.hideKeyboard() {
    clearFocus()
    (context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(windowToken, 0)
}

@KauUtils
fun View.showKeyboard() {
    requestFocus()
    (context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}


@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
@KauUtils
fun View.setRippleBackground(@ColorInt foregroundColor: Int, @ColorInt backgroundColor: Int) {
    background = createSimpleRippleDrawable(foregroundColor, backgroundColor)
}

@KauUtils
inline val View.parentViewGroup: ViewGroup
    get() = parent as ViewGroup

inline val EditText.value: String get() = text.toString().trim()

inline val TextInputEditText.value: String get() = text.toString().trim()

/**
 * Generates a recycler view with match parent and a linearlayoutmanager, since it's so commonly used
 */
fun Context.fullLinearRecycler(rvAdapter: RecyclerView.Adapter<*>? = null, configs: RecyclerView.() -> Unit = {}) = RecyclerView(this).apply {
    layoutManager = LinearLayoutManager(this@fullLinearRecycler)
    layoutParams = RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.MATCH_PARENT)
    if (rvAdapter != null) adapter = rvAdapter
    configs()
}

/**
 * Sets a linear layout manager along with an adapter
 */
fun RecyclerView.withLinearAdapter(rvAdapter: RecyclerView.Adapter<*>) = apply {
    layoutManager = LinearLayoutManager(context)
    adapter = rvAdapter
}

/**
 * Animate a transition a given imageview
 * If it is not shown, the action will be invoked directly and no further actions will be made
 * If it is already shown, scaling and alpha animations will be added to the action
 */
inline fun <T : ImageView> T.fadeScaleTransition(duration: Long = 500L, minScale: Float = 0.7f, crossinline action: T.() -> Unit) {
    if (!isVisible) action()
    else {
        var transitioned = false
        ValueAnimator.ofFloat(1.0f, 0.0f, 1.0f).apply {
            this.duration = duration
            addUpdateListener {
                val x = it.animatedValue as Float
                scaleXY = x * (1 - minScale) + minScale
                imageAlpha = (x * 255).toInt()
                if (it.animatedFraction > 0.5f && !transitioned) {
                    transitioned = true
                    action()
                }
            }
            start()
        }
    }
}

/**
 * Attaches a listener to the recyclerview to hide the fab when it is scrolling downwards
 * The fab will reappear when scrolling has stopped or if the user scrolls up
 */
fun FloatingActionButton.hideOnDownwardsScroll(recycler: RecyclerView) {
    recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {

        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            if (newState == android.support.v7.widget.RecyclerView.SCROLL_STATE_IDLE && !isShown) show()
        }

        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            if (dy > 0 && isShown) hide()
            else if (dy < 0 && isHidden) show()
        }
    })
}

inline var View.scaleXY
    get() = Math.max(scaleX, scaleY)
    set(value) {
        scaleX = value
        scaleY = value
    }

/**
 * Creates an on touch listener that only emits on a short single tap
 */
@SuppressLint("ClickableViewAccessibility")
inline fun View.setOnSingleTapListener(crossinline onSingleTap: (v: View, event: MotionEvent) -> Unit) {
    setOnTouchListener { v, event ->
        when (event.actionMasked) {
            MotionEvent.ACTION_DOWN -> true
            MotionEvent.ACTION_UP -> {
                if (event.eventTime - event.downTime < 100)
                    onSingleTap(v, event)
                true
            }
            else -> false
        }
    }
}