Skip to content

Instantly share code, notes, and snippets.

@AndSky90
AndSky90 / DateAttrDelegate.kt
Created November 16, 2019 14:06
CustomView editable Form factory
class DateAttrDelegate(field: EditText) :
DynamicAttrDelegate(field) {
init {
field.isClickable = false
field.isFocusable = false
field.setOnEditorActionListener { _: TextView, _: Int, _: KeyEvent -> true }
field.setOnClickListener { openDateSelector() }
}
@AndSky90
AndSky90 / StringFormatter.kt
Created November 16, 2019 13:53
Форматтеры дат и имен
object StringFormatter {
private const val ISO_DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss"
fun formatPastTimeDate(dateString: String): String {
val isoString = dateString.substringBefore(".")
val outputTimePattern = SimpleDateFormat("HH:mm", Locale.getDefault())
val outputDateTimePattern = SimpleDateFormat("dd MMM' в 'HH:mm", Locale.getDefault())
val inputPattern = SimpleDateFormat(ISO_DATE_PATTERN, Locale.getDefault())
@AndSky90
AndSky90 / RecyclerView.smoothScroller.kt
Created November 16, 2019 13:52
RecyclerView smoothScroller
fun RecyclerView.smoothSnapToPosition(position: Int) {
val smoothScroller = object : LinearSmoothScroller(this.context) {
override fun getVerticalSnapPreference(): Int {
return SNAP_TO_START
}
override fun getHorizontalSnapPreference(): Int {
return SNAP_TO_START
}
@AndSky90
AndSky90 / Logger
Created November 16, 2019 13:51
Logger
/** отключаемый логгер */
object Logger {
private const val LOGGER_TAG = "===SIB_LOG==="
private val className: String = Logger::class.java.name
fun log() = log(null)
fun log(e: Exception) = log("$e")
@AndSky90
AndSky90 / gist:337a6b81f3ae9b6b614ae72c84e38133
Last active November 16, 2019 13:50
parse RGBA-css3 colors
/**если цвет парсится из строки нормально, возвращаем цвет в Integer, иначе null*/
fun parseItemColor(color: String?): Int? {
return if (color.isNullOrBlank())
null
else
try {
Color.parseColor(color) //парсинг схемы #RRGGBB и #AARRGGBB
} catch (ex: IllegalArgumentException) {
try { //парсинг схемы "rgba(245,245,245,0.5)"
val splitStr = color.substring(color.indexOf('(') + 1, color.indexOf(')'))
class GlideMaskTransformation(private val maskId: Int) : Transformation<Bitmap> {
private val id = "MaskTransformation"
private val paint = Paint().apply { xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN) }
override fun transform(
context: Context, resource: Resource<Bitmap>,
outWidth: Int, outHeight: Int
): Resource<Bitmap> {
require(Util.isValidDimensions(outWidth, outHeight)) { "Cannot apply transformation on width: $outWidth or height: $outHeight" }
@AndSky90
AndSky90 / ExtensionFunctions.kt
Created November 16, 2019 13:47
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()) {
@AndSky90
AndSky90 / FirebaseAnalyticsProvider.kt
Created November 16, 2019 13:44
FirebaseAnalyticsProvider
object FirebaseAnalyticsProvider {
const val AUTH_EVENT = "AUTH_EVENT" //событие при авторизации
const val USER_EVENT = "USER_EVENT" //событие при запросе модели пользователя
const val TOKEN_EVENT = "TOKEN_EVENT" //событие при запросе токена
const val TENANT_EVENT = "TENANT_EVENT" // событие при работе с тенантоами
const val CONTENT_EVENT = "CONTENT_EVENT" // ошибка API получения данных
@Suppress("UNUSED")
const val PARAM_CANCELLED_BY_USER = "CANCELLED_BY_USER"
@AndSky90
AndSky90 / AuthProvider.kt
Created November 16, 2019 13:43
AuthProvider
object AuthProvider {
var token: Token? = null
var isAuthorized: Boolean = false
set(value) {
field = value
SharedPreferencesProvider.setIsAuthorized(value)
}
fun getAuthHeaderValue(): String {
@AndSky90
AndSky90 / ValidatorType.kt
Created November 16, 2019 13:31
Validator types regex patterns
/**перечисление типов валидатора текста*/
enum class ValidatorType(
val regex: Pattern
) {
VALIDATE_NAME(Pattern.compile("^[а-яА-ЯёЁa-zA-Z_ -]+$")),
VALIDATE_EMAIL(Patterns.EMAIL_ADDRESS),
VALIDATE_WEB_URL(Patterns.WEB_URL),
VALIDATE_POSITION(Pattern.compile("^[а-яА-ЯёЁa-z0-9A-Z_ -]*$")),
ANY(Pattern.compile(".*")),