anko android_Android Anko布局

anko android

This is the second part in the series of posts on Android Anko. We had covered the Anko Commons library in the first part. In this tutorial, we’ll be discussing and implementing the Android Anko Layouts module which is a part of the Anko library. Anko is a domain specific language library developed to make Android Development faster and easier using Kotlin.

这是Android Anko系列文章的第二部分。 我们已经在第一部分介绍了Anko Commons库。 在本教程中,我们将讨论和实现Android Anko Layouts模块,该模块是Anko库的一部分。 Anko是一个领域特定的语言库,旨在使用Kotlin更快更轻松地进行Android开发。

Anko布局 (Anko Layouts)

Building UI layouts through XML has always been one of the most challenging parts of Android Development.
It’s not type safe/null safe. Moreover, it takes time and battery to load the XML layouts on your device.

通过XML构建UI布局一直是Android开发最具挑战性的部分之一。
它不是类型安全/无效的。 此外,将XML布局加载到设备上需要花费时间和精力。

Of course, you can develop layouts programmatically in your Activities but even that is complex to do. Thankfully we have Anko Layouts now! You can create a much simpler UI using it. For example we can build the following UI using Anko layouts in our Activity.

当然,您可以在“活动”中以编程方式开发布局,但这甚至很复杂。 幸运的是,我们现在有Anko Layouts! 您可以使用它创建一个更简单的UI。 例如,我们可以在Activity中使用Anko布局构建以下UI。

package net.androidly.androidlyankolayouts

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import org.jetbrains.anko.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
       
      verticalLayout{
            editText { 
                hint = "Enter your name"
            }
            
            button("ECHO"){
                setOnClickListener { 
                    toast("Button clicked")
                }
            }
            
            
        }
   }
}

We’ve created a LinearLayout that displays the elements vertically. Also, inside the Anko Layouts syntax we’ve set the button click listener as well.

我们创建了一个LinearLayout来垂直显示元素。 此外,在Anko Layouts语法内,我们还设置了按钮单击侦听器。

Using Anko Layouts we are able to keep the layout code and the app logic together instead of linking the XML in the activity. The equivalent XML code is:

使用Anko Layouts,我们可以将布局代码和应用程​​序逻辑保持在一起,而不必在活动中链接XML。 等效的XML代码是:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter your name" />


    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ECHO" />
</LinearLayout>

Anko Layouts are a good substitute for XML layouts since it makes the logic easy to write and maintain.
Anko Layouts has its fair share of disadvantages too:

Anko Layouts是XML布局的良好替代品,因为它使逻辑易于编写和维护。
Anko Layouts也有很多缺点:

  • They do not show a preview of the layout like XML. Though you can download the Anko Support plugin from Preferences in Android Studio:
  • Lack of formatting like XML.

    缺乏像XML这样的格式。

Having said that, Anko Layouts does allow you to include XML layouts in the Anko Layouts DSL syntax.

话虽如此,Anko Layouts确实允许您在Anko Layouts DSL语法中包括XML布局。

Let’s dive deep into the various features of Anko Layouts now.

现在让我们深入研究Anko Layouts的各种功能。

入门 (Getting Started)

Add the following dependency in your build.gradle file:

在build.gradle文件中添加以下依赖项:

implementation "org.jetbrains.anko:anko-sdk25:0.10.4"
implementation "org.jetbrains.anko:anko-appcompat-v7:0.10.4"

In place of sdk25 you can also place: sdk15, sdk19, sdk21, sdk23.

代替sdk25您还可以放置: sdk15sdk19sdk21sdk23

The above dependency contains the Anko Common module too.

上面的依赖项也包含Anko Common模块。

布局和布局参数 (Layouts and Layout Params)

You can use all the major view groups we’ve discussed earlier as containers to hold the widgets.

您可以将我们前面讨论的所有主要视图组用作容纳小部件的容器。

Horizontal LinearLayout

水平LinearLayout

linearLayout{
            editText {
                hint = "Enter your name"
            }

            button("ECHO")
            {
                setOnClickListener {
                    toast("Button clicked")
                }
            }
        }

This arranges the views horizontally. The Anko layout looks like:

这将水平排列视图。 Anko布局看起来像:

We can set the Layout Params as:

我们可以将布局参数设置为:

linearLayout {

            layoutParams = ViewGroup.LayoutParams(matchParent, matchParent)
            padding = dip(16)
            this.gravity = Gravity.CENTER
            weightSum = 1.0f
            editText {
                hint = "Enter your name"
                gravity = Gravity.END
            }.lparams(width = 0, height = wrapContent)
            {
                weight = 0.6f
            }

            button("ECHO")
            {
                setOnClickListener {
                    toast("Button clicked")
                }
            }.lparams(width = 0, height = wrapContent) {
                weight = 0.4f
            }


        }

In the above code, we set the widths of the widgets inside LinearLayout by layout weight.
By default, the layoutParams for LinearLayout in the above code were matchParent only so you can get rid of that.

在上面的代码中,我们通过布局权重设置LinearLayout内部小部件的宽度。
默认情况下,上面代码中LinearLayout的matchParent仅是matchParent因此您可以摆脱它。

If you specify lparams(), but omit width and/or height for the widgets, their default values are both wrapContent
如果指定lparams(),但省略了小部件的宽度和/或高度,则它们的默认值均为wrapContent

RelativeLayout

相对布局

val ID_1 = 1

        relativeLayout {

            button {
                id = ID_1
                text = "Button $ID_1"
                gravity =  Gravity.START + Gravity.CENTER_VERTICAL
            }.lparams {
                centerInParent()
            }

            button("Button 2").lparams { below(ID_1) }
            button("Button 3").lparams {
                alignParentBottom()
                alignParentEnd()
            }

        }

Take note that to set more than one gravity, we use + in Anko Layouts. In XML, we used |

请注意,要设置多个重力,我们在Anko Layouts中使用+ 。 在XML中,我们使用|

Try building Anko Layouts with FrameLayout and ScrollView as the root of the layout yourselves!

尝试使用FrameLayout和ScrollView作为自己的布局根来构建Anko布局!

Anko ConstraintLayout (Anko ConstraintLayout)

To use ConstraintLayout in Anko Layouts add the following dependencies in your build.gradle.

要在Anko Layouts中使用ConstraintLayout,请在build.gradle添加以下依赖build.gradle

implementation 'com.android.support.constraint:constraint-layout:1.1.2'
implementation "org.jetbrains.anko:anko-constraint-layout:0.10.4"

Following code demonstrates an Anko Layout with a TextView and an ImageView.

以下代码演示了具有TextView和ImageView的Anko布局。

val ID_11 = 11
        val ID_22 = 22

        constraintLayout {
            val image = imageView(R.mipmap.ic_launcher) {
                id = ID_11
                scaleType = ImageView.ScaleType.CENTER_CROP
            }.lparams(dip(48), dip(48))

            val textLabel = textView {
                id = ID_22
                text = "Hello"
                padding = dip(5)
            }.lparams(wrapContent, wrapContent)



            applyConstraintSet {
                image {
                    connect(
                            ConstraintSetBuilder.Side.TOP to ConstraintSetBuilder.Side.TOP of PARENT_ID,
                            ConstraintSetBuilder.Side.LEFT to ConstraintSetBuilder.Side.LEFT of PARENT_ID,
                            ConstraintSetBuilder.Side.RIGHT to ConstraintSetBuilder.Side.RIGHT of PARENT_ID,
                            ConstraintSetBuilder.Side.BOTTOM to ConstraintSetBuilder.Side.BOTTOM of PARENT_ID
                    )

                    verticalBias = 0.2f

                }

                textLabel {
                    connect(
                            ConstraintSetBuilder.Side.TOP to ConstraintSetBuilder.Side.BOTTOM of image margin dip(10),
                            ConstraintSetBuilder.Side.RIGHT to ConstraintSetBuilder.Side.RIGHT of PARENT_ID margin dip(16),
                            ConstraintSetBuilder.Side.LEFT to ConstraintSetBuilder.Side.LEFT of PARENT_ID margin dip(16)


                    )

                }
            }
        }

In the above code, we’ve set the ImageView to the center of the screen but with a verticalBias.
We’ve added the TextView below it.

在上面的代码中,我们将ImageView设置为屏幕的中心,但带有verticalBias。
我们在其下面添加了TextView。

Anko协调器布局 (Anko CoordinatorLayout)

To use a CoordinatorLayout add the following dependencies in your build.gradle.

要使用CoordinatorLayout,请在build.gradle中添加以下依赖项。

implementation 'com.android.support:design:28.0.0-alpha3'
implementation "org.jetbrains.anko:anko-design:0.10.4"

Note: The above were the versions available at the time of writing this tutorial.

注意:以上是编写本教程时可用的版本。

The following code demonstrates CoordinatorLayout in action using Anko Layouts.

以下代码演示了使用Anko Layouts的CoordinatorLayout。

package net.androidly.androidlyankolayouts

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.AppBarLayout.LayoutParams.*
import android.support.v4.content.ContextCompat
import android.support.v4.view.GravityCompat
import android.view.Gravity
import android.widget.Toolbar
import org.jetbrains.anko.*
import org.jetbrains.anko.design.appBarLayout
import org.jetbrains.anko.design.coordinatorLayout
import org.jetbrains.anko.design.floatingActionButton


class MainActivity : AppCompatActivity() {


    var toolbar: Toolbar? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        coordinatorLayout {

            appBarLayout {
                toolbar = themedToolbar(R.style.ThemeOverlay_AppCompat_Dark_ActionBar) {
                    backgroundResource = R.color.colorPrimary
                    textView {
                        text = "HELLO"
                    }
                }.lparams(width = matchParent) {
                    scrollFlags = SCROLL_FLAG_SNAP or SCROLL_FLAG_SCROLL or SCROLL_FLAG_ENTER_ALWAYS
                }
            }.lparams(width = matchParent)

            floatingActionButton {
                imageResource = android.R.drawable.ic_dialog_email
                backgroundColor = ContextCompat.getColor(ctx, R.color.colorPrimary)
            }
                    .lparams(wrapContent, wrapContent) {
                        gravity = Gravity.BOTTOM or GravityCompat.END
                        horizontalMargin = dip(25)
                        verticalMargin=  dip(25)
                    }
        }

    }
}
  • horizontalMargin sets the margin to the left and right.

    horizontalMargin将边距设置为左右。
  • verticalMargin sets the margin to the top and bottom.

    verticalMargin将边距设置为顶部和底部。
  • topMargin, bottomMargin, leftMargin and rightMargin are used to set margins to individual sides.

    topMarginbottomMarginleftMarginrightMargin用于将边距设置为各个边。

具有自定义视图的警报对话框 (Alert Dialog With Custom View)

package net.androidly.androidlyankolayouts

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.Gravity
import android.widget.EditText
import org.jetbrains.anko.*

class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        verticalLayout {

            var inputName: EditText? = null
            gravity = Gravity.CENTER

            lparams(height = matchParent, width = matchParent) {
                margin = dip(16)
            }

            button {
                text = "Alert Dialog With Edit Text"

                setOnClickListener {
                    alert {
                        title = "Title"
                        message = "Message"

                        customView {
                            inputName = editText {
                                hint = "Enter your name"
                            }
                        }

                        yesButton {
                            toast("Name is ${inputName?.text}")
                        }
                    }.show()
                }
            }

        }

    }
}

主题块 (Themed Blocks)

Anko DSL provides themed versions of all the UI widgets. You can set a pre-defined or custom theme on the widget as:

Anko DSL提供所有UI小部件的主题版本。 您可以在小部件上将预定义或自定义主题设置为:

verticalLayout {
            themedButton("Ok", theme = android.R.style.Widget_Holo_Light_Button)
            themedEditText(theme = android.R.style.TextAppearance_Holo_Widget_EditText)
        }

包含标签 (Include Tag)

We can include XML layout files in the Anko DSL as well:

我们也可以在Anko DSL中包含XML布局文件:

verticalLayout{
include<Button>(R.layout.customButton) {
    backgroundColor = Color.RED
}.lparams(width = matchParent) { padding = dip(12) }
}

The root view of the layout file is specified in the brackets.

布局文件的根视图在方括号中指定。

You can also specify the specific type properties inside the {}

您还可以在{}内指定特定的类型属性

verticalLayout{
include<Button>(R.layout.customButton) {
    backgroundColor = Color.RED
    setOnClickListener{
     toast("")}
}.lparams(width = matchParent) { padding = dip(12) }
}

辅助功能 (Helper Functions)

We can use the applyRecursively function to apply a property recursively to all the elements of the layout.

我们可以使用applyRecursively函数将属性递归地应用于布局的所有元素。

Example:

例:

package net.androidly.androidlyankolayouts

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.widget.Button
import android.widget.TextView
import org.jetbrains.anko.*

class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        verticalLayout {
            button("Button 1")
            textView("TextView 1")
            button("Button 2")
            textView("TextView 2")
        }.applyRecursively { view ->
            when (view) {
                is Button -> view.backgroundColor = ContextCompat.getColor(ctx, R.color.colorPrimary)
                is TextView -> view.textColor = ContextCompat.getColor(ctx, R.color.colorAccent)
            }
        }

    }
}

applyRecursively sets different colors to the different views(Button and TextView) in the above code.

apply在上面的代码中为不同的视图(按钮和文本视图)递归地设置不同的颜色。

Anko组件 (Anko Components)

Till now, we’ve added the Anko Layouts directly inside the Activity’s onCreate function.
using the AnkoComponent interface we can separate the UI part from the Activity.

到目前为止,我们已经将Anko Layouts直接添加到Activity的onCreate函数中。
使用AnkoComponent接口,我们可以将UI部分与Activity分开。

Example:

例:

package net.androidly.androidlyankolayouts

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import org.jetbrains.anko.*

class MainActivity : AppCompatActivity() {

    private val textView by lazy {
        find
   
   
    
    (R.id.myTextView)
    }

    lateinit var mainUI: MainActivityUI

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainUI = MainActivityUI()
        mainUI.setContentView(this)

        mainUI.btn.text = "Hello Anko"
        
        textView.text = "Nice AnkoComponent"


    }
}

class MainActivityUI : AnkoComponent<MainActivity> {


    lateinit var btn: Button


    override fun createView(ui: AnkoContext<MainActivity>): View {


        return with(ui) {
            verticalLayout {
                btn = button("Anko Component")
                {
                    id = R.id.myButton
                    setOnClickListener {
                        toast("Hello Anko Components")
                    }
                }

                textView {
                    id = R.id.myTextView

                }
            }

        }
    }

}


   
   

MainActivityUI().setContentView(this) is used to populate the layout from AnkoComponent class in the Activity.

MainActivityUI().setContentView(this)用于从Activity中的AnkoComponent类填充布局。

We can retrieve the widgets inside the Anko Layout by using find. But this is the same as findViewById of XML.

我们可以使用来检索Anko Layout中的小部件 找。 但这与XML的findViewById相同。

The way we retrieved the Button instance is the recommended way.

推荐的方式是我们检索Button实例的方式。

This brings an end to this tutorial on Android Anko Layouts using Kotlin.

使用Kotlin结束了有关Android Anko Layouts的本教程。

翻译自: https://www.journaldev.com/381/android-anko-layouts

anko android

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值