Kotlin base (B) - DSL

The so-called DSL domain-specific language (Domain Specified Language / DSL), the basic idea is "designed not seek perfection," as the target range covers everything like a general-purpose language software problem, but the problem is specific to a particular computer language.

Kotlin base (B) - DSL

Kotlin DSL Definition: Use Kotlin language developed to solve a specific problem areas, with a unique code structure of the API.

A, DSL

DSL (domain specific language), namely Domain Specific Language: specifically address a particular problem in computer languages ​​such as familiar to everyone, SQL and regular expressions. With DSL programming style, it can make the process more simple and clean, simple and intuitive. Of course, we can also create your own DSL. Compared with the traditional API, DSL is more expressive, more in line with human language habits.

If you create a separate language to solve a specific problem areas, development costs and learning costs are high, so there was the concept of internal DSL. The so-called internal DSL, is the use of general-purpose programming language to build DSL, for example, Kotlin DSL.

1.1 Common DSL

Common DSL can be seen in many areas, such as:

  • Ant build software field
  • HTML UI designer
  • VHDL hardware designer

1.2 general-purpose programming language vs DSL

General-purpose programming language (such as Java, Kotlin, Android, etc.), often provides a comprehensive library to help developers create complete applications, while DSL only focus on one area, such as SQL supports only related processing database, and regular expression type only used to search and replace text, we can not use SQL or regular expression to develop a complete application.

  • DSL for non-programmers to use, for the use of experts in the field;
  • DSL has a higher level of abstraction, not go into detail similar data structures;
  • DSL expression is limited, it can only be described in the field model, the purpose programming language can describe arbitrary model;

Whether it is a common programming languages, or Domain Specific Languages ​​are ultimately to be presented to developers in the form of API. Good, elegant, clean, consistent API style is the pursuit of every good developer, and DSL tend to have a unique code structure and consistent coding style.

Second, the application Kotlin DSL in Android development

2.1 Anko

Anko is a DSL (Domain-Specific Language), which is produced JetBrains, Andrews frame for Kotlin development. Its primary purpose is to replace the previous way to use XML code generation UI layout.

2.1.1 Use

Anko, no other strange inheritance class, as long as the standard of Activity, Fragment, FragmentActivity or any other class

First, using DSL Anko org.jetbrains.anko introducing the class. *.

DSL can be used in onCreate () in which:

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

    verticalLayout {
        padding = dip(30)
        editText {
            hint = "Name"
            textSize = 24f
        }
        editText {
            hint = "Password"
            textSize = 24f
        }
        button("Login") {
            textSize = 26f
        }
    }
}

Do not show call setContentView (R.layout.something), Anko automatically Activity (only for Activity) were set content view

padding, hint textSize and extended properties. Most of these properties have View, allows text = "Some text" instead of setText ( "Some text").

VerticalLayout (a vertical direction LinearLayout), editText and button

Extended functions. These functions exist in most of the frame ANdroid in View, Activities, Fragments (android.support package) Context The same applies even.

If there is a Context instance, DSL can write the following structure:

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

Variable name became EditText type.

2.1.2 Helper Methods

You may have noticed that the front button method took a string parameter, this method is also used Helper TextView, EditText, Button, ImageView.

If you do not need to View other properties, you can omit {} direct write button ( "Ok") or only button ():

verticalLayout {
    button("Ok")
    button("Cancel")
}
2.1.3 Layouts 和 LayoutParams

In the parent layout layout controls you may need to use LayoutParams.xml long this:

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

Anko in LayoutParams achieved using a similar xml View, lparams behind.

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

If lparams specified, but does not specify the width or height, the default is WRAP_CONTENT, but you can specify your own arguments by using named.

Note Here are some handy attributes:

  • horizontalMargin set both left and right margins
  • verticalMargin set both top and bottom
  • margin setting while in four directions margins
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

    <EditText
        android:id="@+id/todo_title"
        android:layout_width="match_parent"
        android:layout_heigh="wrap_content"
        android:hint="@string/title_hint" />

    <!-- Cannot directly add an inline click listener as onClick delegates implementation to the activity -->
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/add_todo" />

</LinearLayout>

After using Anko, can be implemented in code layout and button also bind the click event.

verticalLayout {
    var title = editText {
        id = R.id.todo_title
        hintResource = R.string.title_hint
    }
    button {
        textResource = R.string.add_todo
        onClick { view -> {
                // do something here
                title.text = "Foo"
            }
        }
    }
}

We can see a major advantage of DSL is that it takes very little time to understand and convey more information in a field.

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 
       } 
   } 
 }
Pop 2.1.4
 alert("Hi, I'm Roy", "Have you tried turning it off and on again?") { 
     yesButton { toast("Oh…") } 
     noButton {} 
 }.show()

2.1.5 Asynchronous

 doAsync { 
     // Long background task 
     uiThread { 
         result.text = "Done" 
     } 
 } 

About me
more information you can click + about me , and very much like to share with everyone, and common progress

Guess you like

Origin blog.51cto.com/14541311/2439341