Skip to content

Instantly share code, notes, and snippets.

@ananth10
Last active April 28, 2023 11:48
Show Gist options
  • Save ananth10/a856125ef993b6f67048ae5a32199921 to your computer and use it in GitHub Desktop.
Save ananth10/a856125ef993b6f67048ae5a32199921 to your computer and use it in GitHub Desktop.
Useful Kotlin Extension Functions
fun Activity.goToActivity(newActivity: Class<*>){
val intent= Intent(this, newActivity)
startActivity(intent)
}
fun Activity.goToActivityWithBundle(newActivity: Class<*>,bundle: Bundle){
val intent=Intent(this, newActivity)
intent.putExtra("bundle",bundle)
startActivity(intent)
}
fun Context.hideKeyboard(){
val context=this
val activity=context as Activity
val windowToken=activity.window.decorView.rootView.windowToken
val inputService=getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputService.hideSoftInputFromWindow(windowToken,0)
}
fun View.show(){
this.visibility = View.VISIBLE //e.g TextView.show()
}
fun View.hide() {
this.visibility = View.INVISIBLE //e.g TextView.hide()
}
fun String?.valid() : Boolean = //e.g if(data.valid())
this != null && !this.equals("null", true)
&& this.trim().isNotEmpty()
fun String.isValidEmail(): Boolean
= this.isNotEmpty() && Patterns.EMAIL_ADDRESS.matcher(this).matches(). // e.g val email=test@gmail.com, email.isValidEmail()
fun String.formatPhoneNumber(context: Context, region: String): String? { // e.g val phone=34343, phone.formatPhoneNumber(context,"IN")
val phoneNumberKit = PhoneNumberUtil.createInstance(context)
val number = phoneNumberKit.parse(this, region)
if (!phoneNumberKit.isValidNumber(number))
return null
return phoneNumberKit.format(number, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL)
}
// Activity
inline fun <reified T : Any> Activity.getValue(
lable : String, defaultvalue : T? = null) = lazy{
val value = intent?.extras?.get(lable)
if (value is T) value else defaultvalue
}
inline fun <reified T : Any> Activity.getValueNonNull(
lable : String, defaultvalue : T? = null) = lazy{
val value = intent?.extras?.get(lable)
requireNotNull((if (value is T) value else defaultvalue)){lable}
}
// Fragment
inline fun <reified T: Any> Fragment.getValue(lable: String, defaultvalue: T? = null) = lazy {. //e.g val firstName by getValue<String>("firstName") // String?
val value = arguments?.get(lable)
if (value is T) value else defaultvalue
}
inline fun <reified T: Any> Fragment.getValueNonNull(lable: String, defaultvalue: T? = null) = lazy { //e.g val lastName by getValueNonNull<String>("lastName") // String
val value = arguments?.get(lable)
requireNotNull(if (value is T) value else defaultvalue) { lable }
}
//Resource Extensions
fun Int.asColor() = ContextCompat.getColor(ApplicationCalss.instance, this) // e.g val color = R.color.dark_blie.asColor()
fun Int.asDrawable() = ContextCompat.getDrawable(MavrikApplication.instance, this) // e.g val drawable = R.drawable.launcher.asDrawable()
// Show alert dialog
fun Context.showAlertDialog(positiveButtonLable : String = getString(R.string.okay), // e.g showAlertDialog(message)
title : String = getString(R.string.app_name) , message : String,
actionOnPositveButton : () -> Unit) {
val builder = AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setCancelable(false)
.setPositiveButton(positiveButtonLable) { dialog, id ->
dialog.cancel()
actionOnPositveButton()
}
val alert = builder.create()
alert?.show()
}
// Toash extensions
fun Context.showShotToast(message : String){ //e.g. showShotToast(message)
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
fun Context.showLongToast(message : String){ // e.g showLongToast(message)
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
// Snackbar Extensions
fun View.showShotSnackbar(message : String){ // e.g showShotSnackbar(message)
Snackbar.make(this, message, Snackbar.LENGTH_SHORT).show()
}
fun View.showLongSnackbar(message : String){ //e.g showLongSnackbar(message)
Snackbar.make(this, message, Snackbar.LENGTH_LONG).show()
}
fun View.snackBarWithAction(message : String, actionlable : String, //e.g snackBarWithAction(message, lable)
block : () -> Unit){
Snackbar.make(this, message, Snackbar.LENGTH_LONG)
.setAction(actionlable) {
block()
}
}
fun Context?.isOnline(): Boolean { // e.g if(isOnline())
this?.apply {
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val netInfo = cm.activeNetworkInfo
return netInfo != null && netInfo.isConnected
}
return false
}
fun Context?.isOnline(failBlock : () -> Unit = { globalIntenetFailBock() }, successBlock : () -> Unit ) { // e.g isOnline({},{})
this?.apply {
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val netInfo = cm.activeNetworkInfo
if (netInfo != null && netInfo.isConnected){
successBlock()
}else{
failBlock()
}
}?:failBlock()
}
fun View.hideKeyboard(): Boolean { //e.g textView.hideKeyboard()
try {
val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
return inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
} catch (ignored: RuntimeException) { }
return false
}
fun View.showKeyboard() { //e.g textView.showKeyboard()
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
this.requestFocus()
imm.showSoftInput(this, 0)
}
//Permission
fun Fragment.isGranted(permission: AppPermission) = run { // e.g isGranted(permission)
context?.let {
(PermissionChecker.checkSelfPermission(it, permission.permissionName
) == PermissionChecker.PERMISSION_GRANTED)
} ?: false
}
fun Fragment.shouldShowRationale(permission: AppPermission) = run { // e.g shouldShowRationale(permission)
shouldShowRequestPermissionRationale(permission.permissionName)
}
fun Fragment.requestPermission(permission: AppPermission) { // e.g requestPermission(permission)
requestPermissions(arrayOf(permission.permissionName), permission.requestCode
)
}
fun AppCompatActivity.checkPermission(permission: AppPermission) = run { // e.g checkPermission(permission)
context?.let {
(ActivityCompat.checkSelfPermission(it, permission.permissionName
) == PermissionChecker.PERMISSION_GRANTED)
} ?: false
}
fun AppCompatActivity.shouldRequestPermissionRationale(permission: AppPermission) = // e.g shouldRequestPermissionRationale(permission)
ActivityCompat.shouldShowRequestPermissionRationale(this, permission.permissionName)
fun AppCompatActivity.requestAllPermissions(permission: AppPermission) { //e.g requestAllPermissions(permission)
ActivityCompat.requestPermissions(this, arrayOf(permission.permissionName), permission.requestCode))
}
//Spannable
fun SpannableString.withClickableSpan(clickablePart: String, onClickListener: () -> Unit): SpannableString {
val clickableSpan = object : ClickableSpan() {
override fun onClick(widget: View?) = onClickListener.invoke()
}
val clickablePartStart = indexOf(clickablePart)
setSpan(clickableSpan,
clickablePartStart,
clickablePartStart + clickablePart.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
return this
}
fun TextView.setColorOfSubstring(substring: String, color: Int) {
try {
val spannable = android.text.SpannableString(text)
val start = text.indexOf(substring)
spannable.setSpan(ForegroundColorSpan(ContextCompat.getColor(context, color)), start, start + substring.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
text = spannable
} catch (e: Exception) {
e.printStackTrace()
}
}
fun SpannableStringBuilder.spanText(span: Any): SpannableStringBuilder {
setSpan(span, 0, length, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE)
return this
}
private fun String.toSpannable() = SpannableStringBuilder(this)
fun String.foregroundColor(@ColorInt color: Int): SpannableStringBuilder {
val span = ForegroundColorSpan(color)
return toSpannable().spanText(span)
}
fun String.backgroundColor(@ColorInt color: Int): SpannableStringBuilder {
val span = BackgroundColorSpan(color)
return toSpannable().spanText(span)
}
fun String.relativeSize(size: Float): SpannableStringBuilder {
val span = RelativeSizeSpan(size)
return toSpannable().spanText(span)
}
fun String.supserscript(): SpannableStringBuilder {
val span = SuperscriptSpan()
return toSpannable().spanText(span)
}
fun String.strike(): SpannableStringBuilder {
val span = StrikethroughSpan()
return toSpannable().spanText(span)
}
fun ImageView.loadUrl(url: String) { //e.g imageView.loadUrl(url)
Picasso.with(context).load(url).into(this)
}
fun String.removeFirstLastChar(): String = this.substring(1, this.length - 1) //e.g myString.removeFirstLastChar()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment