Skip to content

Latest commit

 

History

History

core-ktx

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 

core-ktx

Version License

Kotlin extensions in addition to androidx core-ktx.


Installation

Add the dependency:

repositories {
    mavenCentral()
    google()
}

dependencies {
    implementation("com.redmadrobot.extensions:core-ktx:1.6.0-2")
}

Extensions

SharedPreferences

Extensions for SharedPreferences:

  • SharedPreferences.Editor.remove(vararg keys: String): SharedPreferences.Editor

Also, you can use delegates to access values in SharedPreferences:

class ServerPreferencesStorage(
    private val preferences: SharedPreferences
) {
    companion object {
        private const val SERVER_IP = "server.ip"
        private const val SERVER_PORT = "server.port"
    }

    var serverIp: String by preferences.string(SERVER_IP)
    var serverPort: Int by preferences.int(SERVER_PORT)
    
    fun clear() {
        preferences.edit {
            remove(SERVER_IP, SERVER_PORT)
        }
    }
}

Nullable Types

For nullable types you can use functions with suffix Nullable:

string() -> stringNullable()
stringSet() -> stringSetNullable()

Primitive types can't be nullable, so there are no intNullable(), floatNullable(), etc.

Argument Key

By default, the key for getting argument from SharedPreferences is the property name. You can override it with parameter key if you need:

var overrideKey by preferences.boolean("isOverrideKey")

Default Value

If you not assign any value to a property, will be returned default value on property reading. Delegates of nullable types will always return null by default. You can specify default value for non-nullable types with parameter default:

var messagesCount by preferences.int { 1 }
// or
var messagesCount by preferences.int(default = { 1 })

All delegates have default implementation by default:

  • numeric primitives - 0
  • boolean - false
  • String - "" (empty string)
  • String set - empty set

Keyboard

Extension Description
View.isKeyboardVisible: Boolean Returns true if keyboard is visible
Activity.isKeyboardVisible: Boolean Returns true if keyboard is visible
View.showKeyboard() Requests focus and shows keyboard for View if it is possible
View.hideKeyboard() Hides keyboard if it is open
Activity.hideKeyboard() Hides keyboard if it is open

Canvas

  • Canvas.withClipOut(clipPath: Path, block: Canvas.() -> Unit)
  • Canvas.withClipOut(clipRect: Rect, block: Canvas.() -> Unit)
  • Canvas.withClipOut(clipRect: RectF, block: Canvas.() -> Unit)

Contributing

Merge requests are welcome. For major changes, please open an issue first to discuss what you would like to change.