Skip to content

Instantly share code, notes, and snippets.

@AndSky90
Created November 16, 2019 13:47
Show Gist options
  • Save AndSky90/808fc617323499462d980abc75338134 to your computer and use it in GitHub Desktop.
Save AndSky90/808fc617323499462d980abc75338134 to your computer and use it in GitHub Desktop.
Kotlin Extension Functions
@file:Suppress("unused")
/**Заменяет в строке одним символом 2 и более повторяющихся символа пробела, табуляции, абзаца... */
fun String?.removeDuplicateSpaceChars(): String =
if (this.isNullOrBlank()) ""
else this.trim().replace("(\\s)+".toRegex()) { it.value[0].toString() }
/**Форматтер строки адреса к изображению*/
fun String?.formatUrlImageLink(isFullHd: Boolean): String? {
return if (!this.isNullOrBlank()) {
if (this.isDigitsOnly()) {
Settings.IMAGES + this + if (isFullHd) Settings.FULL_HD else Settings.THUMBS
} else this
} else null
}
/**Устанавливает текст в TextView или скрывает TextView, если текст пустой*/
fun TextView.setTextOrInvisible(string: String?) {
if (!string.isNullOrBlank()) {
this.visibility = View.VISIBLE
this.text = string
} else {
this.visibility = View.GONE
}
}
/**Удобный раздуватель макетов*/
fun ViewGroup.inflate(layoutRes: Int, attachToRoot: Boolean = false): View {
return LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot)
}
fun Context.getColorCompat(id: Int) = ContextCompat.getColor(this, id)
fun Fragment.getColorCompat(id: Int) = ContextCompat.getColor(this.context!!, id)
/**Команды скрытия клавиатуры*/
fun Fragment.hideKeyboard() {
activity?.hideKeyboard(view!!)
}
fun Activity.hideKeyboard() {
hideKeyboard(if (currentFocus == null) View(this) else currentFocus)
}
fun Context.hideKeyboard(view: View) {
val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}
fun View.hideKeyboard() {
val inputMethodManager = this.context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}
fun Context.toast(text: String) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}
fun Float.spToPx(): Float = (this * Resources.getSystem().displayMetrics.scaledDensity)
fun Float.dpToPx(): Float = (this * Resources.getSystem().displayMetrics.density)
fun Int.dpToPx(): Int = ((this * Resources.getSystem().displayMetrics.density).roundToInt())
fun Float.pxToDp(): Float = (this / Resources.getSystem().displayMetrics.density)
fun Int.pxToDp(): Int = ((this / Resources.getSystem().displayMetrics.density).roundToInt())
fun AlertDialog.setRelativeWidth(multiplier: Float) {
val lp = WindowManager.LayoutParams()
lp.copyFrom(this.window?.attributes)
lp.width = (UITools.getDisplayXdpi() * multiplier).dpToPx().roundToInt()
this.window?.attributes = lp
}
/**Команды отображения клавиатуры*/
fun View.showKeyboard() {
val inputMethodManager =
this.context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
fun View.showKeyboardAnyway() {
val inputMethodManager =
this.context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(this, InputMethodManager.SHOW_FORCED)
}
fun Activity.setTransparentSystemBar(stubView: View) {
this.window?.statusBarColor = Color.TRANSPARENT
this.window?.setFlags(
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
)
val resourceId = this.resources?.getIdentifier("status_bar_height", "dimen", "android")
if (resourceId != null && resourceId > 0)
stubView.layoutParams.height = this.resources.getDimensionPixelSize(resourceId)
}
/**Функция, возвращающая RxJava.Observable,
* испускающий Boolean-значения:
* true - если введенный в editText текст проходит валидацию
* false - если не проходит */
@SuppressLint("CheckResult")
fun EditText.getIsValidatedObservable(
errorView: View? = null, //необязательная View, показываемая в случае false валидации
validatorType: ValidatorType, //тип валидатора
required: Boolean
): Observable<Boolean> =
this.textChanges()
.skipInitialValue()
.debounce(INPUT_TEXT_DEBOUNCE, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map {
when (it.isValid(validatorType, required)) {
true -> {
/**убираем сообщение об ошибке и меняем цвет подчеркивания на обычный*/
errorView?.visibility = View.GONE
this.background.setColorFilter(
ContextCompat.getColor(this.context, R.color.colorAccent),
PorterDuff.Mode.SRC_ATOP
)
true
}
else -> {
/**показываем сообщение об ошибке и меняем цвет подчеркивания на красный*/
errorView?.visibility = if (it.isNotBlank()) View.VISIBLE else View.GONE
this.background.setColorFilter(
ContextCompat.getColor(this.context, R.color.colorAccentRed),
PorterDuff.Mode.SRC_ATOP
)
false
}
}
}
/**Валидирует строку исходя из переданного типа валидатора*/
fun CharSequence?.isValid(kind: ValidatorType, required: Boolean?): Boolean? =
if (this.isNullOrBlank()) {
if (required == true) null else true
} else {
kind.regex.matcher(this).matches()
}
fun showOkDialog(
title: String? = null,
message: String? = null,
onOkClick: () -> Unit = {},
context: Context
) {
val builder = AlertDialog.Builder(context, R.style.AlertDialogTheme)
if (title != null) builder.setTitle(title)
if (message != null) builder.setMessage(message)
builder.setPositiveButton(context.getString(R.string.button_ok_title)) { _, _ ->
try {
onOkClick()
} catch (t: Throwable) {
log("Dialog error: ${t.printStackTrace()}")
}
}
builder.create().show()
}
fun showYesNoDialog(
title: String,
message: String,
buttonYesText: String,
buttonNoText: String,
positiveAction: () -> Unit = {},
negativeAction: () -> Unit = {},
cancelable: Boolean = false,
context: Context
) {
val dialog = AlertDialog.Builder(context, R.style.AlertDialogTheme)
.setTitle(title)
.setMessage(message)
.setPositiveButton(buttonYesText) { _, _ ->
try {
positiveAction()
} catch (t: Throwable) {
log("Dialog error: ${t.printStackTrace()}")
}
}
.setNegativeButton(buttonNoText) { _, _ ->
try {
negativeAction()
} catch (t: Throwable) {
log("Dialog error: ${t.printStackTrace()}")
}
}
.setCancelable(cancelable)
.create()
dialog.show()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment