Skip to content

Instantly share code, notes, and snippets.

@trfiladelfo
Created May 4, 2018 15:59
Show Gist options
  • Save trfiladelfo/41cccf768bb4e91d7607f309e466c702 to your computer and use it in GitHub Desktop.
Save trfiladelfo/41cccf768bb4e91d7607f309e466c702 to your computer and use it in GitHub Desktop.
Extension methods written in Kotlin useful in daily Android development
@file:JvmName("ExtensionsUtils")
package com.example.piotr.kotlin_project.commons.extension
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.example.piotr.kotlin_project.R
import com.squareup.picasso.Picasso
/**
* @author piotr on 29.07.16.
*/
/**
* Check: http://antonioleiva.com/kotlin-awesome-tricks-for-android/
* For API examples: http://antonioleiva.com/api-request-kotlin/
*/
fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false) : View {
return LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot)
}
fun ImageView.loadImg(imageUrl: String) {
if (TextUtils.isEmpty(imageUrl)) {
Picasso.with(context).load(R.mipmap.ic_launcher).into(this)
} else {
Picasso.with(context).load(imageUrl).into(this)
}
}
fun Activity.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {

Toast.makeText(this, message, duration)
.show()
}
inline fun View.snack(message: String, length: Int = Snackbar.LENGTH_LONG, f: Snackbar.() -> Unit) {
val snack = Snackbar.make(this, message, length)
snack.f()
snack.show()
}
fun Snackbar.action(action: String, color: Int? = null, listener: (View) -> Unit) {
setAction(action, listener)
color?.let { setActionTextColor(color) }
}
/*
The find function belongs to Anko library. But you can do something similar quite easy:
*/
inline fun <reified T : View> Activity.find(id: Int): T = findViewById(id) as T
//create an extension property that returns a list of the views:
val ViewGroup.views: List<View>
get() = (0 until childCount).map { getChildAt(it) }
//use as navigate<DetailActivity>("2")
inline fun <reified T : Activity> Activity.navigate(id: String) {
val intent = Intent(this, T::class.java)
intent.putExtra("id", id)
startActivity(intent)
}
class SquareImageView : ImageView {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val width = getMeasuredWidth()
setMeasuredDimension(width, width)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment