1 Star 0 Fork 0

yohom / anko

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

Download TeamCity (simple build status) GitHub license

Anko logo

Anko is a library which makes Android application development faster and easier. It makes your code clean and easy to read, and lets you forget about rough edges of Android SDK for Java.

Just a brief example. Here is a "hello world" written with Anko:

verticalLayout {
    val name = editText()
    button("Say Hello") {
        onClick { toast("Hello, ${name.text}!") }
    }
}

Code above creates a button inside a LinearLayout and attaches an OnClickListener to that button.

Hello world

As you might have guessed, it's a DSL for Android. It is written in Kotlin.

Contents

Why Anko?

Why DSL?

By default, UI in Android is written using XML. That is inconvenient in the following ways:

  • It is not typesafe
  • It is not null-safe
  • It forces you to write almost the same code for every layout you make
  • XML is parsed on the device wasting CPU time and battery
  • Most of all, it allows no code reuse.

While you can create UI programmatically, it's hardly done because it's somewhat ugly and hard to maintain. Here's a plain Kotlin version (one in Java is even longer):

val act = this
val layout = LinearLayout(act)
layout.orientation = LinearLayout.VERTICAL
val name = EditText(act)
val button = Button(act)
button.text = "Say Hello"
button.setOnClickListener {
    Toast.makeText(act, "Hello, ${name.text}!", Toast.LENGTH_SHORT).show()
}
layout.addView(name)
layout.addView(button)

A DSL makes the same logic easy to read, easy to write and there is no runtime overhead. Here it is again:

verticalLayout {
    val name = editText()
    button("Say Hello") {
        onClick { toast("Hello, ${name.text}!") }
    }
}

Supporting existing code

You don't have to rewrite all your UI with Anko. You can keep your old classes written in Java. Moreover, if you still want (or have) to write a Kotlin activity class and inflate an XML layout for some reason, you can use View properties, which would make things easier:

// Same as findViewById(), simpler to use
val name = find<TextView>(R.id.name)
name.hint = "Enter your name"
name.onClick { /*do something*/ }

You can make your code even more compact by using Kotlin Android Extensions.

How it works

There is no :tophat:. Anko consists of some Kotlin extension functions and properties arranged into type-safe builders, as described under Type Safe Builders.

Since it's somewhat tedious to write all these extensions by hand, they're generated automatically using android.jar files from Android SDK as sources.

Is it extensible?

Short answer: yes.

For example, you might want to use a MapView in the DSL. Then just write this in any Kotlin file from where you could import it:

public inline fun ViewManager.mapView(theme: Int = 0) = mapView(theme) {}
public inline fun ViewManager.mapView(theme: Int = 0, init: MapView.() -> Unit) = ankoView({ MapView(it) }, theme, init)

{ MapView(it) } is a factory function for your custom View. It accepts a Context instance.

So now you can write this:

frameLayout {
    val mapView = mapView().lparams(width = matchParent)
}

Also see Extending Anko if you need to create top-level DSL views.

Using with Gradle

There's a template project showing how to include Anko library into your Android Gradle project.

Basically, all you have to do is to add an additional repository and a compile dependency:

dependencies {
    compile 'org.jetbrains.anko:anko-sdk15:0.9.1' // sdk19, sdk21, sdk23 are also available
    compile 'org.jetbrains.anko:anko-support-v4:0.9.1' // In case you need support-v4 bindings
    compile 'org.jetbrains.anko:anko-appcompat-v7:0.9.1' // For appcompat-v7 bindings
}

Using as Jar library

If your project is not based on Gradle, just attach jars from the releases page or from the jcenter repository as project library dependencies and that's it.

Which Anko libraries are available and which do I need?

If you don't need the DSL features of Anko, you can just reference org.jetbrains.anko:anko-common, and that's all you have to do.

If you need the DSL features of Anko, you need to reference different libraries.

First, you need to reference a main library based on which minSdkVersion you target. anko-common is referenced by those libraries, so you don't need to specify it yourself. Here are the available libraries:

  • org.jetbrains.anko:anko-sdk15 for 15 <= minSdkVersion < 19
  • org.jetbrains.anko:anko-sdk19 for 19 <= minSdkVersion < 21
  • org.jetbrains.anko:anko-sdk21 for 21 <= minSdkVersion < 23
  • org.jetbrains.anko:anko-sdk23 for 23 <= minSdkVersion

Then, for any Android Support library you referenced in your build.gradle, you need to add the matching Anko library, if you want some more Anko magic for those specific Android Support libraries. Here are all available Anko Android Support libraries:

  • org.jetbrains.anko:anko-support-v4
  • org.jetbrains.anko:anko-appcompat-v7
  • org.jetbrains.anko:anko-cardview-v7
  • org.jetbrains.anko:anko-gridlayout-v7
  • org.jetbrains.anko:anko-recyclerview-v7
  • org.jetbrains.anko:anko-design
  • org.jetbrains.anko:anko-percent

Here is an example:

android {
    ...
    defaultConfig {
        ...
        minSdkVersion 15 // Min SDK version is 15 in this example
        targetSdkVersion 23
        ...
    }
    ...
}

dependencies {
    ...
    // Note the used support libs
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.android.support:recyclerview-v7:23.1.1'

    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    compile "org.jetbrains.anko:anko-sdk15:$anko_version" // So here it's 15 too

    // Anko libs matching support libs
    compile "org.jetbrains.anko:anko-appcompat-v7:$anko_version"
    compile "org.jetbrains.anko:anko-design:$anko_version"
    compile "org.jetbrains.anko:anko-recyclerview-v7:$anko_version"
}

Building Anko

Instructions for building Anko are located under Building.

Understanding Anko

As mentioned above, Anko is written in Kotlin. In case you are not familiar with Kotlin, please refer to kotlinlang.org. Kotlin is similar enough to Java, so learning it will be easy.

Basics

In Anko, you don't need to inherit from any special classes: just use standard Activity, Fragment, FragmentActivity or whatever you want.

First of all, import org.jetbrains.anko.* to use Anko DSL in your classes.

DSL is available in onCreate():

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    
    verticalLayout {
        padding = dip(30)
        editText {
            hint = "Name"
            textSize = 24f
        }
        editText {
            hint = "Password"
            textSize = 24f
        }
        button("Login") {
            textSize = 26f
        }
    }
}
:penguin: There's no explicit call to setContentView(R.layout.something): Anko sets content views automatically for Activities (and only for them).

hint and textSize are synthetic extension properties bound to JavaBean-style getters and setters, padding is an extension property from Anko. Either of these exists for most View properties allowing you to write text = "Some text" instead of setText("Some text").

verticalLayout (a LinearLayout but already with a LinearLayout.VERTICAL orientation), editText and button are extension functions. Such functions also exist for almost every View in Android framework, and they work in Activities, Fragments (both default and that from android.support package) and even for Context.

If you have a Context instance, you can write DSL constructs like this:

val name: EditText = with(myContext) {
    editText {
        hint = "Name"
    }
}

AnkoComponent

Although you can use the DSL directly (in onCreate() or everywhere else), without creating any extra classes, it is often convenient to have UI in the separate class. If you use the provided AnkoComponent interface, you also you get a DSL layout preview feature for free.

class MyActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)
        MyActivityUI().setContentView(this)
    }
}

class MyActivityUI : AnkoComponent<MyActivity> {
    override fun createView(ui: AnkoContext<MyActivity>) = with(ui) {
        verticalLayout {
            val name = editText()
            button("Say Hello") {
                onClick { ctx.toast("Hello, ${name.text}!") }
            }
        }
    }
}

Helper methods

As you probably noticed earlier, the button() function in the previous section accepts a String parameter. Such helper methods exist for some views such as TextView, EditText, Button or ImageView.

If you don't need to set any properties for some particular View, you can omit {} and write button("Ok") or even just button():

verticalLayout {
    button("Ok")
    button("Cancel")
}

Layouts and LayoutParams

Positioning of widgets inside parent containers can be tuned using LayoutParams. In XML it looks like this:

<ImageView 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dip"
    android:layout_marginTop="10dip"
    android:src="@drawable/something" />

In Anko, you specify LayoutParams right after a View description using lparams():

linearLayout {
    button("Login") {
        textSize = 26f
    }.lparams(width = wrapContent) {
        horizontalMargin = dip(5)
        topMargin = dip(10)
    }
}

If you specify lparams(), but omit width and/or height, their default values are both WRAP_CONTENT. But you always can pass them explicitly: use named arguments.

Some convenient helper properties to notice:

  • horizontalMargin sets both left and right margins,
  • verticalMargin set top and bottom ones, and
  • margin sets all four margins simultaneously.

Note that lparams() are different for different layouts, for example, in the case of RelativeLayout:

val ID_OK = 1

relativeLayout {
    button("Ok") {
        id = ID_OK
    }.lparams { alignParentTop() }
  
    button("Cancel").lparams { below(ID_OK) }
}

Listeners

You can set listeners from Anko code:

button("Login") {
    onClick {
        login(name, password)
    }
}

It would be the same as this:

button.setOnClickListener(object : OnClickListener {
    override fun onClick(v: View) {
        login(name, password)
    }
})

Anko is very helpful when you have listeners with lots of methods. Consider the following code written without using Anko:

seekBar.setOnSeekBarChangeListener(object: OnSeekBarChangeListener {
    override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
        // Something
    }
    override fun onStartTrackingTouch(seekBar: SeekBar?) {
        // Just an empty method
    }
    override fun onStopTrackingTouch(seekBar: SeekBar) {
        // Another empty method
    }
})

And now with Anko:

seekBar {
    onSeekBarChangeListener {
        onProgressChanged { seekBar, progress, fromUser ->
            // Something
        }
    }
}

If you set onProgressChanged() and onStartTrackingTouch() for the same View, these two "partially defined" listeners will be merged. For the same listener method, last wins.

Resources, Colors and Dimensions

Using resource identifiers

All examples in the previous chapters used raw Java strings, but it is hardly a good practice. Typically you put all your string data into res/values/ directory and access it at runtime calling, for example, getString(R.string.login).

Fortunately, in Anko you can pass resource identifiers both to helper methods (button(R.string.login)) and to extension properties (button { textResource = R.string.login }).

Note that the property name is not the same: instead of text, hint, image, we now use textResource, hintResource and imageResource.

:penguin: Resource properties always throw AnkoException when read.

Colors

Two simple extension functions to make the code more readable.

Function Result
0xff0000.opaque non-transparent red
0x99.gray.opaque non-transparent #999999 gray

Dimensions

You can specify dimension values in dip (density-independent pixels) or in sp (scale-independent pixels): dip(dipValue) or sp(spValue). Note that the textSize property already accepts sp (textSize = 16f). Use px2dip and px2sp to convert backwards.

Instance shorthands

Sometimes you need to pass a Context instance to some Android SDK method from your Activity code. Usually you can just use this, but what if you're inside the inner class? You would probably write SomeActivity.this in case of Java and this@SomeActivity if you're writing in Kotlin.

With Anko you can just write ctx. It is an extension property which works both inside Activity and Service and is even accessible from Fragment (it uses getActivity() method under the hood). You can also get an Activity instance using act extension property.

UI wrapper

Before the Beginning of Time Anko always used UI tag as a top-level DSL element:

UI {
    editText {
        hint = "Name"
    }
}

You can still use this tag if you want. And it would be much easier to extend DSL as you have to declare only one ViewManager.customView function. See Extending Anko for more information.

Include tag

It is easy to insert an XML layout into DSL. Use the include() function:

include<View>(R.layout.something) {
    backgroundColor = Color.RED
}.lparams(width = matchParent) { margin = dip(12) }

You can use lparams() as usual, and if you provide a specific type instead of View, you can also use this type inside {}:

include<TextView>(R.layout.textfield) {
    text = "Hello, world!"
}

Styles

Anko supports styling: applyRecursively() is simply a function that accepts View, is applied for the View itself, and then recursively to each child of a View if it is a ViewGroup:

verticalLayout {
    editText {
        hint = "Name"
    }
    editText {
        hint = "Password"
    }
}.applyRecursively { view -> when(view) {
    is EditText -> view.textSize = 20f
}}
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} 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.

简介

暂无描述 展开 收起
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/yohom_342/anko.git
git@gitee.com:yohom_342/anko.git
yohom_342
anko
anko
master

搜索帮助