Skip to content

Instantly share code, notes, and snippets.

@nicemak
Last active February 11, 2020 07:10
Show Gist options
  • Save nicemak/6bd718045f7c5232c2239399b153e26b to your computer and use it in GitHub Desktop.
Save nicemak/6bd718045f7c5232c2239399b153e26b to your computer and use it in GitHub Desktop.
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.Drawable
import android.os.Handler
import android.text.Editable
import android.text.Spannable
import android.text.SpannableString
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.util.TypedValue
import android.view.HapticFeedbackConstants
import android.view.View
import android.view.animation.AnimationUtils
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.ListView
import android.widget.TextView
import androidx.annotation.DrawableRes
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import coil.ImageLoader
import coil.api.load
import coil.decode.GifDecoder
import coil.size.Scale
import coil.util.CoilUtils
import com.robinhood.ticker.TickerUtils
import com.robinhood.ticker.TickerView
import okhttp3.OkHttpClient
fun View.makeVisible() { this.visibility = View.VISIBLE }
fun View.makeInvisible() { this.visibility = View.INVISIBLE }
fun View.makeGone() { this.visibility = View.GONE }
fun View.enable() { isEnabled = true }
fun View.disable() { isEnabled = false }
fun View.isVisible() : Boolean = this.visibility == View.VISIBLE
fun View.playAnimation(anim : Int) { startAnimation(AnimationUtils.loadAnimation(context, anim)) }
fun View.setViewBackgroundWithoutResettingPadding(@DrawableRes backgroundResId: Int) {
val paddingBottom = this.paddingBottom
val paddingStart = ViewCompat.getPaddingStart(this)
val paddingEnd = ViewCompat.getPaddingEnd(this)
val paddingTop = this.paddingTop
setBackgroundResource(backgroundResId)
ViewCompat.setPaddingRelative(this, paddingStart, paddingTop, paddingEnd, paddingBottom)
}
fun TickerView.setTextWithAnimation(text: String)
{
// implementation 'com.robinhood.ticker:ticker:2.0.2'
setCharacterLists(TickerUtils.provideNumberList())
setPreferredScrollingDirection(TickerView.ScrollingDirection.ANY)
animationDuration = 2000
setText(text,true)
}
fun View.setViewBackgroundWithoutResettingPadding(background: Drawable?) {
val paddingBottom = this.paddingBottom
val paddingStart = ViewCompat.getPaddingStart(this)
val paddingEnd = ViewCompat.getPaddingEnd(this)
val paddingTop = this.paddingTop
ViewCompat.setBackground(this, background)
ViewCompat.setPaddingRelative(this, paddingStart, paddingTop, paddingEnd, paddingBottom)
}
fun View.setDelayClick(delay: Long)
{
isEnabled = false
Handler().postDelayed({ isEnabled = true }, delay)
}
fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
this.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun afterTextChanged(editable: Editable?) {
afterTextChanged.invoke(editable.toString())
}
})
}
fun View.showKeyboard(show: Boolean) {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
if (show) {
if (requestFocus()) imm.showSoftInput(this, 0)
} else {
imm.hideSoftInputFromWindow(windowToken, 0)
}
}
/**
* Remember to add this permission to the Manifest:
* <uses-permission android:name="android.permission.VIBRATE"/>
*/
inline fun View.consumeButtonWithHapticFeedback(lambda: () -> Unit) {
lambda()
this.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
}
fun TextView.bold() {
paint.isFakeBoldText = true
paint.isAntiAlias = true
}
fun TextView.deleteLine() {
paint.flags = paint.flags or Paint.STRIKE_THRU_TEXT_FLAG
paint.isAntiAlias = true
}
fun TextView.underLine() {
paint.flags = paint.flags or Paint.UNDERLINE_TEXT_FLAG
paint.isAntiAlias = true
}
fun ImageView.setImage(image: String, animated: Boolean) {
if (animated)
{
// Image Loader for playing GIFs
val imageLoaderAnimated = ImageLoader(context) {
componentRegistry { add(GifDecoder()) }
okHttpClient { OkHttpClient.Builder().cache(CoilUtils.createDefaultCache(context)).build() }
}
// Loading image/animated gif to imageView
this.load(image, imageLoaderAnimated) {
crossfade(750)
scale(Scale.FILL)
}
}
else
{
val imageLoader = ImageLoader(context) {
okHttpClient { OkHttpClient.Builder().cache(CoilUtils.createDefaultCache(context)).build() }
}
this.load(image, imageLoader) {
scale(Scale.FILL)
}
}
}
fun TextView.setColouredSpan(word: String, color: Int) {
val spannableString = SpannableString(text)
val start = text.indexOf(word)
val end = text.indexOf(word) + word.length
try {
spannableString.setSpan(ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
text = spannableString
} catch (e: IndexOutOfBoundsException) {
println("'$word' was not not found in TextView text")
}
}
fun TextView.setSize(size: Float) { setTextSize(TypedValue.COMPLEX_UNIT_SP, size) }
fun RecyclerView.disableItemAnimator() {
(itemAnimator as? SimpleItemAnimator)?.supportsChangeAnimations = false
}
fun ListView.justifyListViewHeightBasedOnChildren() {
val adapter = adapter ?: return
val vg = this
val desiredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.UNSPECIFIED)
var totalHeight = 0
for (i in 0 until adapter.count-1) {
val listItem = adapter.getView(i, null, vg)
listItem.measure(0, 0)
totalHeight += listItem.measuredHeight
}
val par = layoutParams
par.height = totalHeight + (dividerHeight * (adapter.count - 1))
layoutParams = par
requestLayout()
}
fun View.getScreenShot(): Bitmap {
val returnedBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(returnedBitmap)
val bgDrawable = background
if (bgDrawable != null) bgDrawable.draw(canvas)
else canvas.drawColor(Color.WHITE)
draw(canvas)
return returnedBitmap
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment