Skip to content

Instantly share code, notes, and snippets.

@vamjakuldip
Last active September 29, 2020 07:07
Show Gist options
  • Save vamjakuldip/a180d3e4d9e76ac035068b000f2deaf2 to your computer and use it in GitHub Desktop.
Save vamjakuldip/a180d3e4d9e76ac035068b000f2deaf2 to your computer and use it in GitHub Desktop.
Android View Extension, Snackbar extension, shake view and vibrate device.
package com.vk.android.extension
import android.content.Context
import android.os.Build
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import com.google.android.material.snackbar.Snackbar
import com.vk.android.R
import com.vk.android.utils.EventMsg
fun View.showSnackbar(msg: String, timeLength: Int) {
Snackbar.make(this, msg, timeLength).run {
setActionTextColor(ContextCompat.getColor(this.context, R.color.colorAccent))
this.config(context)
show()
}
}
fun View.setupSnackbar(lifecycleOwner: LifecycleOwner, snackbarEvent: LiveData<EventMsg<String>>, timeLength: Int) {
snackbarEvent.observe(lifecycleOwner, Observer { event ->
event.getContentIfNotHandled()?.let {
showSnackbar(it, timeLength)
}
})
}
fun Snackbar.config(context: Context) {
val params = this.view.layoutParams as ViewGroup.MarginLayoutParams
params.setMargins(12, 12, 12, 12)
this.view.layoutParams = params
this.view.background = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
context.getDrawable(R.drawable.bg_snackbar)
} else {
AppCompatResources.getDrawable(context, R.drawable.bg_snackbar)
}
ViewCompat.setElevation(this.view, 6f)
}
fun View.visible() {
visibility = View.VISIBLE
}
fun View.invisible() {
visibility = View.INVISIBLE
}
fun View.gone() {
visibility = View.GONE
}
fun View.inflate(res: Int, parent: ViewGroup? = null): View {
return LayoutInflater.from(this.context).inflate(res, parent, false)
}
fun View.shake() {
val shake = TranslateAnimation(0f, 10f, 0f, 0f)
shake.interpolator = CycleInterpolator(7f)
shake.duration = 500
this.startAnimation(shake)
}
fun View.vibrate(milliseconds: Long) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
(this.context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator).vibrate(VibrationEffect.createOneShot(milliseconds, VibrationEffect.DEFAULT_AMPLITUDE))
} else {
(this.context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator).vibrate(milliseconds)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment