Anko Kotlin Library

repository·master·Indexed 12 days ago

https://github.com/kotlin/anko

A deprecated Kotlin library designed to accelerate Android development. It provides a type-safe DSL for layouts to replace XML, a SQLite query DSL, coroutine utilities based on kotlinx.coroutines, and helpers for common Android SDK tasks such as Intents, Dialogs, and Logging.

Tokens
5.3K
Snippets
15
Records
22
Agent score
95%

What's inside Anko

  1. Overview of Anko components

    master

    Anko is a library designed to make Android development faster and cleaner by providing helpers for the Android SDK. It is divided into four main parts:

    1. Anko Commons: Helpers for Intents, Dialogs, Toasts, Logging, and Resources.
    2. Anko Layouts: A DSL for writing dynamic, type-safe Android layouts without XML.
    3. Anko SQLite: A query DSL and parser for Android SQLite.
    4. Anko Coroutines: Utilities based on kotlinx.coroutines.
  2. Use Anko Coroutines utilities

    master

    Anko Coroutines provides utilities built on top of kotlinx.coroutines:

    • bg(): Executes code in a common pool.
    • asReference(): Creates a weak reference wrapper. This protects against memory leaks in asynchronous frameworks that do not support cancellation by preventing coroutines from holding strong references to captured objects until they finish or are canceled.
  3. Understand property types for Anko Layouts helpers

    master

    When using Anko's layout DSL helpers, properties are mapped to Android widget methods. The helper constructors use Java-style type notation: primitive types are lowercase (e.g., int, boolean) and nullable types do not use question marks (e.g., CharSequence instead of CharSequence?).

    Common property mappings include:

    • Button / CheckBox / TextView / EditText: Use text with CharSequence or int (for resource IDs).
    • CheckBox: Also supports a checked property of type boolean.
    • ImageView / ImageButton: Use imageDrawable with type Drawable or imageResource with type int.
  4. Install specific Anko modules via Gradle

    master

    If you do not want the full library, you can import individual components. Common modules include:

    • Anko Commons: anko-commons
    • Anko Layouts: anko-sdk25 (other versions like sdk15, sdk19, sdk21, sdk23 are available) or anko-appcompat-v7.
    • Anko Coroutines: anko-sdk25-coroutines or anko-appcompat-v7-coroutines.
    • Anko SQLite: anko-sqlite.

    Specific artifacts are also available for Android support libraries like CardView-v7, Design, GridLayout-v7, Percent, RecyclerView-v7, and ConstraintLayout.

    dependencies {
        // Anko Commons
        implementation "org.jetbrains.anko:anko-commons:$anko_version"
    
        // Anko Layouts
        implementation "org.jetbrains.anko:anko-sdk25:$anko_version"
        implementation "org.jetbrains.anko:anko-appcompat-v7:$anko_version"
    
        // Coroutine listeners for Anko Layouts
        implementation "org.jetbrains.anko:anko-sdk25-coroutines:$anko_version"
        implementation "org.jetbrains.anko:anko-appcompat-v7-coroutines:$anko_version"
    
        // Anko SQLite
        implementation "org.jetbrains.anko:anko-sqlite:$anko_version"
    }
  5. Install Anko in a Gradle project

    master

    You can include Anko in your Android project using Gradle. You can either use the meta-dependency to include all features at once, or include specific modules to keep your project lightweight.

    Note: Anko is deprecated.

    // To include all features (Commons, Layouts, SQLite, Coroutines)
    dependencies {
        implementation "org.jetbrains.anko:anko:$anko_version"
    }
    
    ext.anko_version='0.10.8'
  6. Migrate from Anko to modern alternatives

    master

    Anko is officially deprecated. Depending on which part of the Anko library you were using, you should migrate to the following modern alternatives:

    Layout DSL

    If you used Anko Layouts for building Android layouts via a type-safe DSL, migrate to:

    • Jetpack Compose: A reactive View DSL for Kotlin, backed by Google.
    • Splitties (Views DSL): An extensible View DSL that resembles the Anko experience.

    Generic utilities

    If you used Anko Commons for utility functions and classes, migrate to:

    • Android KTX: A set of Kotlin extensions for various Android purposes, backed by Google.
    • Splitties: A collection of micro-libraries for various use cases.

    SQLite helpers

    If you used Anko SQLite for database access, migrate to:

    • Room: An annotation-based framework for SQLite database access, backed by Google.
    • SQLDelight: A type-safe API generator for SQL queries.
  7. Define constraints using the ConstraintSetBuilder DSL

    master

    The ConstraintSetBuilder allows you to define relationships between views within a ConstraintLayout. You can target views by their ID or by the View object itself.

    Connecting Views

    Connections are created using the of and to infix functions. You can define a basic connection or a connection with a margin.

    • Basic Connection: Side.LEFT of viewId to Side.RIGHT of targetId
    • Margin Connection: (Side.LEFT of viewId to Side.RIGHT of targetId).margin(16)

    View Properties

    Inside a view's configuration block, you can set various properties:

    • Dimensions: width, height, maxWidth, maxHeight, minWidth, minHeight, defaultWidth, defaultHeight.
    • Bias & Weight: horizontalBias, verticalBias, horizontalWeight, verticalWeight.
    • Transformations: alpha, rotationX, rotationY, scaleX, scaleY, translationX, translationY, translationZ, transformPivotX, transformPivotY.
    • Other: visibility, dimensionRatio, applyElevation, elevation.

    Clearing Constraints

    Use clear() to remove all constraints from a view, or clear(sideId) to remove a constraint from a specific side.

    Match Constraint

    Use the matchConstraint property to set a dimension to MATCH_CONSTRAINT (equivalent to 0 in ConstraintLayout params).

    constraintLayout.applyConstraintSet {
        val view1Id = R.id.view1
        val view2Id = R.id.view2
    
        view1Id {
            width = ConstraintLayout.matchConstraint
            height = 100
            // Connect view1's left to parent's start
            (Side.START of this@ConstraintSetBuilder) to (Side.START of view1Id).margin(16)
        }
    
        view2Id {
            // Connect view2's top to view1's bottom
            (Side.TOP of this@ConstraintSetBuilder) to (Side.BOTTOM of view1Id)
        }
    }
  8. Use Anko SQLite for database queries

    master

    Anko SQLite simplifies working with Android SQLite databases by providing a query DSL and parser collection, removing the need to manually parse results using Android cursors.

    fun getUsers(db: ManagedSQLiteOpenHelper): List<User> = db.use {
        db.select("Users")
                .whereSimple("family_name = ?", "John")
                .doExec()
                .parseList(UserParser)
    }
  9. Use Anko Layouts DSL

    master

    Anko Layouts provides a type-safe DSL for writing dynamic Android layouts without XML. It supports standard layouts like verticalLayout and specialized layouts like ConstraintLayout (since v0.10.4).

    Listeners like onClick accept suspend lambdas, allowing you to write asynchronous code directly within the UI definition.

    verticalLayout {
        val name = editText()
        button("Say Hello") {
            onClick { toast("Hello, ${name.text}!") }
        }
    }
  10. Reference property signatures for Anko Layouts

    master

    The following list defines the available property signatures used by Anko's layout DSL helpers. Note that types follow Java conventions (lowercase primitives, no question marks for nullables).

    android.widget.Button text:CharSequence
    android.widget.Button text:int
    android.widget.CheckBox text:CharSequence
    android.widget.CheckBox text:int
    android.widget.CheckBox text:CharSequence, checked:boolean
    android.widget.CheckBox text:int, checked:boolean
    android.widget.TextView text:CharSequence
    android.widget.TextView text:int
    android.widget.EditText text:CharSequence
    android.widget.EditText text:int
    android.widget.ImageView imageDrawable:Drawable
    android.widget.ImageView imageResource:int
    android.widget.ImageButton imageDrawable:Drawable
    android.widget.ImageButton imageResource:int
  11. Create list-based dialogs with AlertDialogBuilder

    master

    To create a dialog that presents a list of items for the user to select, use the items or adapter methods. These methods require a callback that receives the index (which) of the selected item.

    Using a List of Strings

    items(listOf("Option 1", "Option 2", "Option 3")) { which -> 
        // 'which' is the index of the selected item
    }

    Using an Android Resource Array

    items(R.array.my_options_array) { which -> 
        // 'which' is the index of the selected item
    }

    Using a ListAdapter or Cursor

    • adapter(adapter: ListAdapter, callback: (which: Int) -> Unit)
    • adapter(cursor: Cursor, labelColumn: String, callback: (which: Int) -> Unit)