A collection of useful extension methods for Android

Overview

Kotlin Jetpack Android Arsenal

A collection of useful extension methods for Android

Arguments Bindings

public class ArgumentsFragment : Fragment() {
  public companion object {
    public fun newInstance(): ArgumentsFragment = ArgumentsFragment().apply {
      arguments = Bundle().apply {
        putBoolean("extra_boolean", true)
      }
    }
  }
  
  // Required binding without default value
  val booleanOrThrow by bindArgument<Boolean>("extra_boolean")

  // Required binding with default value
  val booleanOrDefault by bindArgument<Boolean>("extra_boolean", false)

  // Optional binding
  val booleanOrNull by bindOptionalArgument<Boolean>("extra_boolean")
}

These methods can be used with Activity, Fragment, and support library Fragment subclasses. You can also implement ArgumentsAware interface to provide a custom arguments source. Full list of supported bindings:

  • bindArgument<Boolean> / bindOptionalArgument<Boolean>
  • bindArgument<Double> / bindOptionalArgument<Double>
  • bindArgument<Int> / bindOptionalArgument<Int>
  • bindArgument<Long> / bindOptionalArgument<Long>
  • bindArgument<String> / bindOptionalArgument<String>
  • bindArgument<CharSequence> / bindOptionalArgument<CharSequence>
  • bindArgument<Float> / bindOptionalArgument<Float>
  • bindArgument<Enum> / bindOptionalArgument<Enum>
  • bindArgument<Parcelable> / bindOptionalArgument<Parcelable>
  • bindArgument<Serializable> / bindOptionalArgument<Serializable>

Every bindXXXArgument returns a ReadWriteProperty so they can be used with var's as well. In this case you don't have to deal with Bundle at all. No explicit Bundle creation, no silly EXTRA_XXX constants, no annoying Bundle.putXXX and Bundle.getXXX calls. Everything just works:

public class UserProfileFragment : Fragment() {
  public companion object {
    public fun newInstance(): UserProfileFragment = UserProfileFragment().apply {
      this.firstName = "Vladimir"
      this.lastName = "Mironov"
    }
  }
  
  // extra name is automatically inferred from property name ("firstName" in this case)
  var firstName by bindArgument<String>()

  // you can also provide a default value using "default" named argument
  var lastName by bindArgument<String>(default = "")
}

Gradle dependency:

compile "com.github.vmironov.jetpack:jetpack-bindings-arguments:0.14.2"

Preferences Bindings

public class PreferencesFragment : Fragment() {
  // Boolean preference
  var boolean by bindPreference<Boolean>("boolean", false)

  // Float preference
  var float by bindPreference<Float>("float", 0.0f)

  // Integer preference
  var integer by bindPreference<Int>("integer", 1)

  // Long preference
  var long by bindPreference<Long>("long", 1L)

  // String preference
  var string by bindPreference<String>("string", "default")
}

These methods can be used with Context, Fragment, support library Fragment, View, and ViewHolder subclasses. The example above uses a default SharedPreferences instance. You can always provide a custom one by implementing PreferencesAware interface:

public class PreferencesFragment : Fragment() {
  val preferences = PreferencesAware {
    activity.getSharedPreferences("CustomSharedPreferences", Context.MODE_PRIVATE)
  }
  
  var boolean by preferences.bindPreference<Boolean>("boolean", false)
  var float by preferences.bindPreference<Float>("float", 0.0f)
  var integer by preferences.bindPreference<Int>("integer", 1)
  var long by preferences.bindPreference<Long>("long", 1L)
  var string by preferences.bindPreference<String>("string", "default")
  
  // Optional preferences are supported as well
  var optionalLong by preferences.bindOptionalPreference<Long>()
  var optionalString by preferences.bindOptionalPreference<String>()
}

Although only Boolean, Float, Int, Long and String preferences are supported by default, the library can be easily extented to support custom type of preference. Adapter interface can be implemented in order to convert any type to a supported one. Here is an example how to imlement json-based preferences using Gson:

public inline fun <reified E : Any> Any.bindGsonPreference(default: E, key: String? = null): ReadWriteProperty<Any, E> {
  return bindPreference(default, GsonPreferenceAdapter(E::class.java), key)
}

public inline fun <reified E : Any> Any.bindGsonPreference(noinline default: () -> E, key: String? = null): ReadWriteProperty<Any, E> {
  return bindPreference(default, GsonPreferenceAdapter(E::class.java), key)
}

public class GsonPreferenceAdapter<T>(val clazz: Class<T>, val gson: Gson = GsonPreferenceAdapter.GSON) : Adapter<T, String> {
  override fun type(): Class<String> = String::class.java
  override fun fromPreference(preference: String): T = gson.fromJson(preference, clazz)
  override fun toPreference(value: T): String = gson.toJson(value)

  public companion object {
    public val GSON = Gson()
  }
}

Usage:

public data class Profile(val firstName: String? = null, val lastName: String? = null)

public class ProfileManager(val context: Context) {
  public var profile by bindGsonPreference(Profile())
}

Gradle dependency:

compile "com.github.vmironov.jetpack:jetpack-bindings-preferences:0.14.2"

Resources Bindings

public class ResourcesFragment : Fragment() {
  // Boolean resource binding
  val boolean by bindResource<Boolean>(R.boolean.boolean_resource)

  // Color resource binding
  val color by bindResource<Int>(R.color.color_resource)

  // Drawable resource binding #1
  val bitmap by bindResource<BitmapDrawable>(R.drawable.drawable_bitmap)
  
  // Drawable resource binding #2
  val vector by bindResource<VectorDrawable>(R.drawable.drawable_vector)

  // Dimension resource binding
  val dimension by bindResource<Int>(R.dimen.dimen_resource)

  // String resource binding
  val string by bindResource<String>(R.string.string_resource)
}

These methods can be used with Activity, Context, Fragment, support library Fragment, View, and ViewHolder subclasses. You can also implement ResourcesAware interface to provide a custom resources source. Full list of supported bindings:

  • bindResource<Boolean>(R.boolean.boolean_resource)
  • bindResource<Int>(R.integer.integer_resource)
  • bindResource<Int>(R.color.color_resource)
  • bindResource<ColorStateList>(R.color.color_resource)
  • bindResource<Drawable>(R.drawable.drawable_resource)
  • bindResource<Int>(R.dimen.dimen_resource)
  • bindResource<Float>(R.dimen.dimen_resource)
  • bindResource<String>(R.string.string_resource)
  • bindResource<CharSequence>(R.string.string_resource)
  • bindResource<IntArray>(R.array.array_resource)
  • bindResource<Array<String>>(R.array.array_resource)
  • bindResource<Array<CharSequence>>(R.array.array_resource)

Gradle dependency:

compile "com.github.vmironov.jetpack:jetpack-bindings-resources:0.14.2"

License

Copyright 2015 Vladimir Mironov

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
You might also like...
An extension of EditText with pin style written in Kotlin
An extension of EditText with pin style written in Kotlin

pin-edittext An extension of EditText with pin style Usage Include PinCodeEditText in your layout XML com.oakkub.android.PinEditText android:layo

A set of extension properties on Int, Long, Double, and Duration, that makes it easier to work with Kotlin Duration

Kotlin Duration Extensions Gradle Groovy repositories { mavenCentral() } implementation 'com.eygraber:kotlin-duration-extensions:1.0.1' Kotlin rep

Write a Ghidra Extension without using Java or Eclipse!

Ghidra Extension in Kotlin using IntelliJ IDEA Write a Ghidra Extension without using Java or Eclipse! Setup Hit Use this template at the top of the r

A Burp extension to find stuff ¯\_(ツ)_/¯
A Burp extension to find stuff ¯\_(ツ)_/¯

FindStuffer FindStuffer, a Burp extension to find stuff, both for Community and Pro versions. You can use FindStuffer to aggregate as many text querie

Jackson extension for Mojang's NBT format

Jackson NBT Data Format Implements Mojang's NBT format in jackson. Usage Using this format works just like regular jackson, but with the ObjectMapper

A collection of small utility functions to make it easier to deal with some otherwise nullable APIs on Android.

requireKTX requireKTX is a collection of small utility functions to make it easier to deal with some otherwise nullable APIs on Android, using the sam

An Easy-to-use Kotlin based Customizable Modules Collection with Material Layouts by BlackBeared.
An Easy-to-use Kotlin based Customizable Modules Collection with Material Layouts by BlackBeared.

Fusion By BlackBeared An Easy-to-use Kotlin based Customizable Library with Material Layouts by @blackbeared. Features Custom Floating Action Buttons

A collection of hand-crafted extensions for your Kotlin projects.

Splitties Splitties is a collection of small Kotlin multiplatform libraries (with Android as first target). These libraries are intended to reduce the

A curated collection of splendid gradients made in Kotlin
A curated collection of splendid gradients made in Kotlin

Gradients A curated collection of splendid gradients made in Kotlin (port of https://webgradients.com for Android). Only linear gradients included for

Comments
  • naming

    naming

    Why do you add bind before any delegation? there is not Kotlin stdlib delegation that start with bind. val booleanOrThrow: Boolean by booleanArgument("extra_boolean")

    also for resources, I think it is more readable:

    val text by stringResource(R.string.text)
    val number by intResource(R.integer.number)
    val dimenPixelSize by dimenResource(R.dimen.size)
    val color by colorResource(R.color.red)
    val intArray by intArrayResource(R.array.ids)
    val stringArray by stringArrayResource(R.array.options)
    val drawable by drawableResource(R.drawable.background)
    
    opened by yoavst 10
  • Rethink arguments bindings

    Rethink arguments bindings

    Early draft:

    class UserArguments(extras: Bundle) : WithExtras(extras) {
      var name by argument<String>()
      var age by argument<Int>()
    }
    
    class UserActivity : AppCompatActivity() {
      private val args by arguments<UserArguments>()
    }
    
    class UserFragment : Fragment() {
      private val args by arguments<UserArguments>()
    }
    
    fun onNavigateToUserScreen(activity: Activity) {
      activity.startActivity(Jetpack.newIntent<UserActivity, UserArguments>(activity) {
        name = "Mike"
        age = 22
      })
    }
    
    inline fun <reified A : WithExtras> Activity.arguments(): ReadOnlyProperty<Activity, A> {
      throw UnsupportedOperationException()
    }
    
    inline fun <reified A : WithExtras> Fragment.arguments(): ReadOnlyProperty<Fragment, A> {
      throw UnsupportedOperationException()
    }
    
    open class WithExtras(val extras: Bundle) {
      inline fun <reified T> argument(name: String? = null, default: T? = null): ReadWriteProperty<Any, T> {
        throw UnsupportedOperationException()
      }
    }
    
    object Jetpack {
      inline fun <reified A : Activity, reified E : WithExtras> newIntent(context: Context, builder: E.() -> Unit): Intent {
        throw UnsupportedOperationException()
      }
    
      inline fun <reified F : Fragment, reified E : WithExtras> newFragment(builder: E.() -> Unit): F {
        throw UnsupportedOperationException()
      }
    }
    
    opened by nsk-mironov 0
  • Bigfixes, framework updates, support for font resources.

    Bigfixes, framework updates, support for font resources.

    • fixed potentially broken vector drawables on pre-lollipop devices
    • added support for font resources introduced with supportlib-v26
    • broke ResourcesAware interface as it now requires Pair<Context, Resources> instead of just Resources
    opened by MrBIMC 0
Releases(0.14.2)
Owner
Vladimir Mironov
Vladimir Mironov
Most used extension methods for Kotlin

Extensify Most used extension methods for Kotlin Download Step 1. Add the JitPack repository to your build file allprojects { repositories {

Mobven 36 Aug 25, 2022
A kotlin library of extension functions that add smalltalk style methods to objects.

KtTalk A kotlin library of extension functions that add smalltalk style methods to objects. Motivation Smalltalk is a pure OO language in which everyt

null 11 Oct 16, 2021
A library provides some useful kotlin extension functions

ktext ?? A library provides some useful kotlin extension functions. Including in your project Gradle Add below codes to your root build.gradle file (n

热心市民苏苏仔 76 Oct 26, 2022
Kstr is a set of helpful methods library for Kotlin intended for make the developer life easier.

Kstr is a set of helpful methods library for Kotlin intended for make the developer life easier. Kstr uses the powerful feature of extension func

Rafael Acioly 0 Nov 3, 2021
A flutter plugin to scan stripe readers and connect to the them and get the payment methods.

stripe_terminal A flutter plugin to scan stripe readers and connect to the them and get the payment methods. Installation Android No Configuration nee

Aawaz Gyawali 8 Dec 29, 2022
Andorid app which provides a bunch of useful Linux commands.

Linux Command Library for Android The app currently has 3203 manual pages, 1351 one-line scripts and a bunch of general terminal tips. It works 100% o

Simon Schubert 276 Dec 31, 2022
WolfxPaper - A Paper fork designed for Wolfx Survial, may useful for some Semi-Vanilla Server

WolfxPaper A Paper fork designed for Wolfx Survial, may useful for some "Semi-Va

TenkyuChimata 1 Jan 19, 2022
A library with many useful and easy-to-use features

This library was made as a replacement for qLib and in the future cubed. These 2 plugins are hard to get you hands on and one of them has many outdated methods so this is a more modern version of those things

Max 1 May 6, 2022
Extension functions over Android's callback-based APIs which allows writing them in a sequential way within coroutines or observe multiple callbacks through kotlin flow.

callback-ktx A lightweight Android library that wraps Android's callback-based APIs into suspending extension functions which allow writing them in a

Sagar Viradiya 171 Oct 31, 2022
Gits-android-extensions - A collection of Kotlin extensions to simplify Android development

gits-android-extensions A collection of Kotlin extensions to simplify Android de

GITS Indonesia 3 Feb 3, 2022