Last active
March 2, 2021 12:42
-
-
Save radeshf/32c536d791676c76580424eb3929c1ee to your computer and use it in GitHub Desktop.
a bunch of kotlin helpful extentions i use in my code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@file:JvmName("ExtensionsUtils") | |
/** | |
* created by radesh farokhmanesh | |
*/ | |
//#1 | |
fun <T> Activity.goTo(cls:Class<T>,finish: Boolean = true){ | |
startActivity(Intent(this,cls)) | |
if (finish) finish() | |
} | |
fun <T> Fragment.goTo(cls:Class<T>, finish: Boolean = true, stringExtras: HashMap<String,String>? = null, intExtras: HashMap<String,Int>?= null, booleanExtra:HashMap<String,Boolean>?=null){ | |
val intent = Intent(requireActivity(),cls) | |
stringExtras?.asIterable()?.forEach { intent.putExtra(it.key,it.value) } | |
intExtras?.asIterable()?.forEach { intent.putExtra(it.key,it.value) } | |
booleanExtra?.asIterable()?.forEach { intent.putExtra(it.key,it.value) } | |
startActivity(intent) | |
if (finish) requireActivity().finish() | |
} | |
//#2 | |
fun Activity.showToast(msg:String){ | |
Toast.makeText(this,msg,Toast.LENGTH_LONG).show() | |
} | |
fun Fragment.showToast(msg:String){ | |
Toast.makeText(requireContext(),msg,Toast.LENGTH_LONG).show() | |
} | |
//#2 | |
fun Context.showToast(msg:String){ | |
Toast.makeText(this,msg,Toast.LENGTH_LONG).show() | |
} | |
fun ViewGroup.inflate(layoutId : Int ,attachToRoot:Boolean = false) : View { | |
return LayoutInflater.from(context).inflate(layoutId,this,attachToRoot) | |
} | |
fun RecyclerView.init(lm: RecyclerView.LayoutManager){ | |
setHasFixedSize(true) | |
layoutManager = lm | |
} | |
fun RecyclerView.init(isVertical: Boolean = true){ | |
setHasFixedSize(true) | |
vertical(isVertical) | |
} | |
fun RecyclerView.vertical(isVertical: Boolean){ | |
layoutManager = when { | |
isVertical -> LinearLayoutManager(context,RecyclerView.VERTICAL,false) | |
else -> LinearLayoutManager(context,RecyclerView.HORIZONTAL,false) | |
} | |
} | |
fun <T> RecyclerView.getAdp() : T{ | |
return adapter as T | |
} | |
fun TextView.setNumberFont(){ | |
typeface = Typeface.createFromAsset(context.assets, "fonts/IRANYekanRegularFaNum.ttf") | |
} | |
fun TextView.setLogoTypeFont(){ | |
typeface = Typeface.createFromAsset(context.assets, "fonts/AdobeArabicShin.ttf") | |
} | |
fun TextView.setTextColorWithAnimation(@ColorInt toColor: Int, duration: Long = 300){ | |
val colorAnim = ObjectAnimator.ofInt(this, "textColor", this.currentTextColor, toColor) | |
colorAnim.setEvaluator(ArgbEvaluator()) | |
colorAnim.duration = duration | |
colorAnim.start() | |
} | |
fun ImageView.setTintColorWithAnimation( fromColor: Int, toColor: Int,duration: Long = 300){ | |
val colorAnim = ObjectAnimator.ofFloat(0f, 1f) | |
colorAnim.addUpdateListener { animation -> | |
val mul = animation.animatedValue as Float | |
val argb = ArgbEvaluator().evaluate(mul, | |
ContextCompat.getColor(context, fromColor), | |
ContextCompat.getColor(context, toColor) | |
) | |
setColorFilter(argb as Int, PorterDuff.Mode.SRC_IN) | |
} | |
colorAnim.duration = duration | |
colorAnim.start() | |
} | |
fun doOnTry(func: () -> Unit, onCatch: (() -> Unit)? = null){ | |
try { | |
func() | |
}catch (e: java.lang.Exception){ | |
e.printStackTrace() | |
onCatch?.invoke() | |
} | |
} | |
fun isAbove(SDK: Int): Boolean { | |
return Build.VERSION.SDK_INT >= SDK | |
} | |
fun TextView.setTextWithAnimation(text : String,duration : Long = 60L){ | |
animate().setDuration(duration).alpha(0f).withEndAction { | |
this@setTextWithAnimation.text = text | |
animate().setDuration(duration).alpha(1f) | |
} | |
} | |
fun ImageView.clickAnimation(duration: Long = 200){ | |
animate().setDuration(duration).alpha(0f).withEndAction { animate().setDuration(duration).alpha(1f) } | |
} | |
fun ImageView.setImageWithAnimation(resId: Int, duration: Long = 100L){ | |
animate().setDuration(duration).alpha(0f).withEndAction { | |
this@setImageWithAnimation.setImageResource(resId) | |
animate().setDuration(duration).alpha(1f) | |
} | |
} | |
fun getDimenForView(context: Context,id:Int) : Int = (context.resources.getDimension(id) / context.resources.displayMetrics.density).toInt() | |
fun ImageView.dropDownAnimation(dropDown: Boolean) { | |
val arrowAnimation: RotateAnimation = if (dropDown) { | |
RotateAnimation(0f, 180f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f) | |
} else { | |
RotateAnimation(180f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f) | |
} | |
arrowAnimation.fillAfter = true | |
arrowAnimation.duration = 300 | |
this.startAnimation(arrowAnimation) | |
} | |
fun TextView.setTextCounterAnimation(text : String){ | |
val duration = 100L | |
animate().setDuration(duration).translationY(-100f).alpha(0f).withEndAction { | |
this@setTextCounterAnimation.text = text | |
animate().setDuration(duration).translationY(100f).translationY(0f).alpha(1f) | |
} | |
} | |
fun View.changeVisibility(visibility: Int, direction : Int = 0) { | |
val duration = 300 | |
if (visibility == View.GONE) { | |
animate() | |
.translationY(when (direction) { | |
Gravity.TOP -> -height.toFloat() | |
Gravity.BOTTOM -> height.toFloat() | |
else -> 0f | |
}) | |
.translationX(when(direction) { | |
Gravity.START -> -width.toFloat() | |
Gravity.END -> width.toFloat() | |
else -> 0f | |
}) | |
.alpha(0.0f) | |
.setDuration(duration.toLong()) | |
.setListener(object : Animator.AnimatorListener { | |
override fun onAnimationStart(animator: Animator) { | |
} | |
override fun onAnimationEnd(animator: Animator) { | |
this@changeVisibility.visibility = visibility | |
} | |
override fun onAnimationCancel(animator: Animator) { | |
} | |
override fun onAnimationRepeat(animator: Animator) { | |
} | |
}) | |
} else if (visibility == View.VISIBLE) { | |
alpha = 0f | |
animate() | |
.translationY(0f) | |
.translationX(0f) | |
.alpha(1.0f) | |
.setDuration(duration.toLong()) | |
.setListener(object : Animator.AnimatorListener { | |
override fun onAnimationStart(animator: Animator) { | |
this@changeVisibility.visibility = visibility | |
} | |
override fun onAnimationEnd(animator: Animator) { | |
} | |
override fun onAnimationCancel(animator: Animator) { | |
} | |
override fun onAnimationRepeat(animator: Animator) { | |
} | |
}) | |
} | |
} | |
fun <T> Observable<T>.networkSchedulers(): Observable<T> { | |
return subscribeOn(Schedulers.io()) | |
.observeOn(AndroidSchedulers.mainThread()) | |
} | |
fun <T> Observable<T>.delayEach(interval: Long, timeUnit: TimeUnit): Observable<T> = | |
Observable.zip(this,Observable.interval(interval, timeUnit), BiFunction { t1, _ -> t1 }) | |
fun SharedPreferences.saveString(key:String,value: String){ | |
edit().putString(key,value).apply() | |
} | |
fun FragmentManager.changeTo( | |
container: Int, fragment: Fragment, addToBackStack:Boolean = true, animationGravity: Int = Gravity.END | |
, sharedElements: HashMap<View,String>? = null ){ | |
val transactions = beginTransaction() | |
if (addToBackStack){ | |
transactions.addToBackStack(null) | |
} | |
when (animationGravity) { | |
Gravity.END -> transactions.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left,R.anim.slide_in_left, R.anim.slide_out_right) | |
Gravity.BOTTOM -> transactions.setCustomAnimations(R.anim.slide_in_top, R.anim.fade_out,R.anim.fade_in, R.anim.slide_out_top) | |
Gravity.CENTER -> transactions.setCustomAnimations(R.anim.fade_in, R.anim.fade_out,R.anim.fade_in, R.anim.fade_out) | |
Gravity.START -> transactions.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right,R.anim.slide_in_right, R.anim.slide_out_left) | |
else -> { | |
} | |
} | |
if (sharedElements != null &&isAbove(Build.VERSION_CODES.LOLLIPOP)) { | |
sharedElements.forEach { | |
transactions.addSharedElement(it.key, it.value) | |
} | |
} | |
transactions | |
.replace(container, fragment) | |
.commit() | |
} | |
fun Activity.setEventBus(register:Boolean){ | |
if (register){ | |
if (!EventBus.getDefault().isRegistered(this)) { | |
EventBus.getDefault().register(this) | |
} | |
}else{ | |
if (EventBus.getDefault().isRegistered(this)) { | |
EventBus.getDefault().unregister(this) | |
} | |
} | |
} | |
fun Fragment.setEventBus(register:Boolean){ | |
if (register){ | |
if (!EventBus.getDefault().isRegistered(this)) { | |
EventBus.getDefault().register(this) | |
} | |
}else{ | |
if (EventBus.getDefault().isRegistered(this)) { | |
EventBus.getDefault().unregister(this) | |
} | |
} | |
} | |
fun Context.getColorR(@ColorRes color: Int): Int { | |
return ContextCompat.getColor(this, color) | |
} | |
fun Context.getDrawableR(@DrawableRes drawable: Int): Drawable? { | |
return ContextCompat.getDrawable(this, drawable) | |
} | |
fun Context.checkSinglePermission(permission: String) : Boolean { | |
return ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED | |
} | |
fun Fragment.showOnMap(lat: Double, lng: Double){ | |
requireContext().showOnMap(lat, lng) | |
} | |
fun Context.showOnMap(lat: Double, lng: Double){ | |
doOnTry({ | |
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?daddr=$lat,$lng")) | |
startActivity(Intent.createChooser(intent, "Choose")) | |
}) | |
} | |
fun View.visibleByBoolean(visible: Boolean) { | |
this.visibility = if (visible) View.VISIBLE else View.GONE | |
} | |
fun Long.toMoneyString(): String { | |
return NumberFormat.getNumberInstance(Locale.getDefault()).format(this) | |
} | |
fun ImageView.loadPicasso(url: String){ | |
Picasso.get() | |
.load(url) | |
.placeholder(R.mipmap.ic_launcher) | |
.error(R.mipmap.ic_launcher) | |
.into(this) | |
} | |
fun TextView.loadHtml(msg: String){ | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { | |
text = Html.fromHtml(msg, Html.FROM_HTML_MODE_LEGACY) | |
} else { | |
text = Html.fromHtml(msg) | |
} | |
} | |
fun Context.getFilesDirFixed(): File { | |
for (a in 0..9) { | |
val path = applicationContext.filesDir | |
if (path != null) { | |
return path | |
} | |
} | |
try { | |
val info: ApplicationInfo = applicationContext.applicationInfo | |
val path = File(info.dataDir, "files") | |
path.mkdirs() | |
return path | |
} catch (e: Exception) { | |
e.printStackTrace() | |
} | |
return File("/data/data/${BuildConfig.APPLICATION_ID}/files") | |
} | |
fun Intent.printExtras(){ | |
val bundle = extras | |
if (bundle != null) { | |
for (key in bundle.keySet()) { | |
Timber.e("$key + : + ${if (bundle[key] != null) bundle[key] else "NULL"}") | |
} | |
} | |
} | |
un Context.openInBrowser(url: String){ | |
doOnTry({ | |
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) | |
}) | |
} | |
fun Context.shareText(text: String){ | |
doOnTry({ | |
val intent = Intent(Intent.ACTION_SEND) | |
intent.type = "text/plain" | |
intent.putExtra(Intent.EXTRA_TEXT, text) | |
startActivity(Intent.createChooser(intent, "Share")) | |
}) | |
} | |
fun RecyclerView.setDivider(@DrawableRes drawableRes: Int) { | |
val divider = DividerItemDecoration(this.context, DividerItemDecoration.VERTICAL) | |
val drawable = ContextCompat.getDrawable(this.context, drawableRes) | |
drawable?.let { | |
divider.setDrawable(it) | |
addItemDecoration(divider) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment