알아두면 좋은 Kotlin extension

2023. 7. 26. 11:09개발/Android

💡
자주 사용하는 extension들을 모아봤다

showToast()

fun Context.showToast(message: String) {
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}

hideKeyboard()

fun View.hideKeyboard() {
    val inputMethodManager = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}

loadUrl()

fun WebView.loadUrl(url: String?) {
    if (!url.isNullOrEmpty()) {
        loadUrl(url)
    }
}

isNetworkConnected()

fun Context.isNetworkConnected(): Boolean {
    val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val networkInfo = connectivityManager.activeNetworkInfo
    return networkInfo != null && networkInfo.isConnected
}

isPermissionGranted()

fun Context.isPermissionGranted(permission: String): Boolean {getFormattedDate() - formats a date into a string:
    return ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
}

getFormattedDate()

fun Date.getFormattedDate(): String {
    val dateFormat = SimpleDateFormat("dd MMM yyyy", Locale.getDefault())
    return dateFormat.format(this)
}

toBitmap()

fun Drawable.toBitmap(): Bitmap {
    val bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmap)
    setBounds(0, 0, canvas.width, canvas.height)
    draw(canvas)
    return bitmap
}

toDp()

fun Context.toDp(px: Int): Float {
    return px / resources.displayMetrics.density
}

toPx()

fun Context.toPx(dp: Int): Int {
    return (dp * resources.displayMetrics.density).toInt()
}

getScreenWidth()

fun Context.getScreenWidth(): Int {
    val displayMetrics = resources.displayMetrics
    return displayMetrics.widthPixels
}

View.visible() / View.gone()

fun View.visible() {
    visibility = View.VISIBLE
}

fun View.gone() {
    visibility = View.GONE
}

EditText.afterTextChanged()

fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
    addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable) {
            afterTextChanged.invoke(s.toString())
        }
        
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
    })
}

View.inflate()

fun ViewGroup.inflate(layoutRes: Int): View {
    return LayoutInflater.from(context).inflate(layoutRes, this, false)
}

SharedPreferences.get() / SharedPreferences.put()

inline fun <reified T : Any> SharedPreferences.get(key: String, defaultValue: T? = null): T? {
    val value = when (T::class) {
        String::class -> getString(key, defaultValue as? String) as T?
        Int::class -> getInt(key, defaultValue as? Int ?: -1) as T?
        Long::class -> getLong(key, defaultValue as? Long ?: -1L) as T?
        Float::class -> getFloat(key, defaultValue as? Float ?: -1f) as T?
        Boolean::class -> getBoolean(key, defaultValue as? Boolean ?: false) as T?
        else -> throw IllegalArgumentException("Unsupported type: ${T::class.java}")
    }
    return value
}

inline fun <reified T : Any> SharedPreferences.put(key: String, value: T?) {
    val editor = edit()
    when (T::class) {
        String::class -> editor.putString(key, value as? String)
        Int::class -> editor.putInt(key, value as? Int ?: -1)
        Long::class -> editor.putLong(key, value as? Long ?: -1L)
        Float::class -> editor.putFloat(key, value as? Float ?: -1f)
        Boolean::class -> editor.putBoolean(key, value as? Boolean ?: false)
        else -> throw IllegalArgumentException("Unsupported type: ${T::class.java}")
    }
    editor.apply()
}

loadImage()

fun ImageView.loadImage(url: String?) {
    Glide.with(this)
        .load(url)
        .placeholder(R.drawable.placeholder)
        .error(R.drawable.error)
        .into(this)
}

isNullOrEmpty()

fun String?.isNullOrEmpty(): Boolean {
    return this == null || this.isEmpty()
}

toEditable()

fun String.toEditable(): Editable = Editable.Factory.getInstance().newEditable(this)


Uploaded by N2T

'개발 > Android' 카테고리의 다른 글

Connectivity Manager  (0) 2023.07.28
AAC  (0) 2023.07.26
Android Macrobenchmark  (0) 2023.07.26
Baseline Profiles  (0) 2023.07.26
Fragment 에서 데이터를 주고받는 방법  (0) 2023.07.26