Kotlin for Android Developers


Kotlin Android Extensions



tải về 1.04 Mb.
Chế độ xem pdf
trang14/79
Chuyển đổi dữ liệu01.11.2023
Kích1.04 Mb.
#55505
1   ...   10   11   12   13   14   15   16   17   ...   79
kotlin-for-android-developers-Ve2A1vRFHnmqGFAn

Kotlin Android Extensions plugins.
1
apply plugin: 'com.android.application'
2
apply plugin: 'kotlin-android'
3
apply plugin: 'kotlin-android-extensions'
4
5
android {
6
...
7
}
8
9
dependencies {
10
compile "com.android.support:appcompat-v7:$support_version"
11
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"


3 Creating a new project
13
12
compile "org.jetbrains.anko:anko-common:$anko_version"
13
}
14
15
buildscript {
16
repositories {
17
jcenter()
18
}
19
dependencies {
20
classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_versio\
21
n"
22
}
23
}
Anko is a library that uses the power of Kotlin to simplify some tasks with Android. We’ll need more
Anko parts later on, but for now it’s enough if we just add
anko-common
. This library is split into
several smaller ones so that we don’t need to include everything if we don’t use it.
3.3 Convert MainActivity to Kotlin code
An interesting feature the Kotlin plugin includes is the ability to convert from Java to Kotlin code.
As any automated process, it won’t be perfect, but it will help a lot during your first days until you
start getting used to Kotlin language.
So we are using it in our
MainActivity.java
class. Open the file and select
Code -> Convert Java
File to Kotlin File
. Take a look at the differences, so that you start becoming familiar with the
language.
3.4 Test that everything works
We’re going to add some code to test Kotlin Android Extensions are working. I’m not explaining
much about it yet, but I want to be sure this is working for you. It’s probably the trickiest part in
this configuration.
First, go to
activity_main.xml
and set an id for the
TextView
:
1
2
android:id="@+id/message"
3
android:text="@string/hello_world"
4
android:layout_width="wrap_content"
5
android:layout_height="wrap_content"/>
Now, add the synthetic import to the activity (don’t worry if you don’t understand much about it
yet):


3 Creating a new project
14
1
import kotlinx.android.synthetic.main.activity_main.*
At
onCreate
, you can now get access to that
TextView
directly:
1
override fun onCreate(savedInstanceState: Bundle?) {
2
super.onCreate(savedInstanceState)
3
setContentView(R.layout.activity_main)
4

tải về 1.04 Mb.

Chia sẻ với bạn bè của bạn:
1   ...   10   11   12   13   14   15   16   17   ...   79




Cơ sở dữ liệu được bảo vệ bởi bản quyền ©hocday.com 2024
được sử dụng cho việc quản lý

    Quê hương