欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

适用于初学者的Android Hello World Kotlin应用程序

程序员文章站 2024-03-19 11:29:46
...

Kotlin has become the recommended and official language for android development. In this tutorial, we will learn how to create a Hello World Android app in Kotlin.

Kotlin已成为Android开发的推荐和官方语言。 在本教程中,我们将学习如何在Kotlin中创建Hello World Android应用。

创建Android Hello World Kotlin应用 (Creating Android Hello World Kotlin App)

You need Android Studio and JDK version 6 or higher installed in order to build and run an android application. If you’re unaware of Android Studio do visit this tutorial before proceeding ahead.
Let’s start building our Hello World Android Application by starting Android Studio.

适用于初学者的Android Hello World Kotlin应用程序

您需要安装Android Studio和JDK版本6或更高版本才能构建和运行android应用程序。 如果您不了解Android Studio,请先阅读教程,然后再继续。
让我们通过启动Android Studio开始构建Hello World Android应用程序。

The package name naming appends the application name to the reverse of the company domain name. Take note that we’ve checked Include Kotlin Support so that the default classes are originally written in Kotlin (.kt).
Set the path of the project to whatever you like! (I’ve done so for mine).

程序包名称命名将应用程序名称附加到公司域名的相反名称。 请注意,我们已经选中了包括Kotlin支持,以便默认类最初是用Kotlin(.kt)编写的。
将项目的路径设置为您喜欢的任何内容! (我已经这样做了)。

Select the Target Android Devices from the next screen. You can set the minimum SDK version as per your choice.
Following are the Android OS Versions currently available:

在下一个屏幕中选择目标Android设备 。 您可以根据需要设置最低SDK版本。
以下是当前可用的Android OS版本:

  • Android 1.0 and 1.1 were not publicly named.

    Android 1.0和1.1未公开命名。
  • Cupcake: Android 1.5

    纸杯蛋糕:Android 1.5
  • Donut: Android 1.6

    甜甜圈:Android 1.6
  • Eclair: Android 2.0–2.1

    埃克莱尔:Android 2.0–2.1
  • Froyo: Android 2.2

    Froyo:Android 2.2
  • Gingerbread: Android 2.3

    姜饼:Android 2.3
  • Honeycomb: Android 3.0–3.2

    蜂窝:Android 3.0–3.2
  • Ice Cream Sandwich: Android 4.0

    冰淇淋三明治:Android 4.0
  • Jelly Bean: Android 4.1–4.3

    果冻豆:Android 4.1–4.3
  • KitKat: Android 4.4

    KitKat:Android 4.4
  • Lollipop: Android 5.0–5.1

    棒棒糖:Android 5.0–5.1
  • Marshmallow: 6.0

    棉花糖:6.0
  • Nougat: Android 7.0

    牛轧糖:Android 7.0
  • Oreo: Android 8.0

    奥利奥:Android 8.0

选择活动类型 (Choosing Activity Type)

Choose the activity type from the next screen.

适用于初学者的Android Hello World Kotlin应用程序

从下一个屏幕中选择活动类型。

Note: An Activity is whatever you see on a single screen in your application(At least on a high level that’s what it is). We’re selecting an Empty Activity right now.

注意 :“活动”就是您在应用程序的单个屏幕上看到的任何内容(至少是在高层次上)。 我们现在选择一个空的活动。

You can customize the Activity name and equivalent layout file name from the next screen as shown below.

适用于初学者的Android Hello World Kotlin应用程序

您可以在下一个屏幕中自定义活动名称和等效的布局文件名称,如下所示。

The layout file is typically hooked to an Activity and is used to display the UI of the activity. The layout file is written in XML.

布局文件通常挂接到活动,并用于显示活动的UI。 布局文件是用XML编写的。

Kotlin Android App项目结构 (Kotlin Android App Project Structure)

Once the platform loads, the following is the project structure you should see.

适用于初学者的Android Hello World Kotlin应用程序

平台加载后,以下是您应看到的项目结构。

项目目录的内容 (Project Directories Contents)

The core logic of our application goes inside the app module
app | src | main

我们应用程序的核心逻辑位于应用程序模块内部
应用| src | 主要

  • The java folder contains the classes(ironically a kotlin class file is residing now!). To enhance the readability of the project structure you can always create a kotlin folder that keeps all the Kotlin class files.

    java文件夹包含类(具有讽刺意味的是,现在存在一个kotlin类文件!)。 为了提高项目结构的可读性,您始终可以创建一个保留所有Kotlin类文件的kotlin文件夹。
  • The res folder contains the resources of the application. By resources we mean the following:
    • drawable: Drawable is something that can be drawn on the screen. It can be an image or a vector asset.
      In the above project structure there are two drawable folders : drawable and drawable-v24. images, vector, and SVG assets set in drawable-v24 would be used for devices with the Android API level equal to and greater than 24. In other words, if the same filename is present in both the folders, for API level above 24 the drawable-v24 file would be used.
      Alternatively, we can create different drawable folders for different screen densities. drawable-ldpi, drawable-mdpi, drawable-hdpi, drawable-xhdpi, drawable-xxhdpi are used for low, medium, high, extra high, extra extra high densities respectively.
    • layout : The layout folder contains the xml files for the views and layouts of the application.
    • mipmap: mipmap folder is specifically used to store app launcher icons. It’s similiar to drawable folder in other cases.

    res文件夹包含应用程序的资源。 所谓资源,是指:
    • drawable :Drawable是可以在屏幕上绘制的东西。 它可以是图像或矢量资产。
      在上述项目结构中,有两个drawable文件夹: drawabledrawable-v24 。 在drawable-v24中设置的图像,矢量和SVG资产将用于Android API级别等于或大于24的设备。换句话说,如果两个文件夹中都存在相同的文件名,则对于24以上的API级别,将使用drawable-v24文件。
      另外,我们可以为不同的屏幕密度创建不同的可绘制文件夹。 drawable-ldpidrawable-mdpidrawable-hdpidrawable-xhdpidrawable-xxhdpi分别用于低,中,高,超高和超高密度。
    • layout :layout文件夹包含用于应用程序的视图和布局的xml文件。
    • mipmap :mipmap文件夹专门用于存储应用启动器图标。 在其他情况下,它类似于可绘制文件夹。
  • The values folder contains the following xml files:
    • styles.xml: It defines the styles and themes of the Activities and it’s subcomponents
    • colors.xml: It defines the color palettes that would eventually be used in the UI stuff
    • strings.xml: Harcoded strings are entered here. They can be accessed using the key name defined.
    • dimens.xml: We define the margins, texts and other view sizes here. Use of standard dimensions is recommended.

    values文件夹包含以下xml文件:
    • styles.xml :它定义活动及其子组件的样式和主题
    • colors.xml :它定义了最终将在UI内容中使用的调色板
    • strings.xml :在此处输入经过编码的字符串。 可以使用定义的键名来访问它们。
    • dimens.xml :我们在此处定义页边距,文本和其他视图大小。 建议使用标准尺寸。
  • The AndroidManifest.xml file contains the essential information related to the application. The activity names, permissions, services etc all are declared here. It can easily be termed as the blueprint of the application.

    AndroidManifest.xml文件包含与应用程序相关的基本信息。 活动名称,权限,服务等均在此处声明。 它可以轻松地称为应用程序的蓝图。
  • Gradle is a general-purpose build tool. The app module’s build.gradle is a build script that contains the dependencies and plugins required in building the application. The root build.gradle contains the dependencies that are required by all modules in the project(including the app module).

    Gradle是通用构建工具。 应用程序模块的build.gradle是一个构建脚本,其中包含构建应用程序所需的依赖项和插件。 根build.gradle包含项目中所有模块(包括app模块)所需的依赖项。
  • Proguard: proguard-rules.pro files resides in the root of the project. It is used for two primary purposes:
    • Shrinking of Code and Resources to minimize the APK size: Code shrinking is available with ProGuard, which detects and removes unused classes, fields, methods, and attributes from your app, including those from included libraries. We can specify rules inside the proguard-rules file specific to each build variant. In all, it optimises the bytecode and removes the unused resources
    • Code Obfuscation: Proguard helps in obfuscating your code thus make your code difficult to reverse engineer and hence makes it secure.

    Proguard :proguard-rules.pro文件位于项目的根目录中。 它用于两个主要目的:
    • 缩小代码和资源以最小化APK大小 :ProGuard可以进行代码缩小,ProGuard可以从您的应用程序中检测并删除未使用的类,字段,方法和属性,包括从包含的库中删除那些类,字段,方法和属性。 我们可以在每个构建变体专用的proguard-rules文件内指定规则。 总之,它优化了字节码并删除了未使用的资源
    • 代码混淆 :Proguard有助于混淆您的代码,从而使您的代码难以进行反向工程,从而使其安全。

The androidTest and test folders should contain the code for unit testing the application.

androidTest和test文件夹应包含用于对应用程序进行单元测试的代码。

androidTest和测试文件夹之间的区别 (Difference between androidTest and test folders)

The androidTest folder contains the unit testing code related to Android Framework.
The test folder contains unit testing code involving pure java/kotlin classes.

androidTest文件夹包含与Android Framework相关的单元测试代码。
测试文件夹包含涉及纯java / kotlin类的单元测试代码。

Android Hello World Kotlin代码 (Android Hello World Kotlin Code)

Let’s look at what the layout file i.e. activity_main.xml looks like:

让我们看一下布局文件(即activity_main.xml样子:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="net.androidly.helloworldkotlin.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

ConstraintLayout acts as a parent view inside which we can place subviews relative to the constraint positions of each other. We’ll go into its details in a later tutorial.

ConstraintLayout充当父视图,在其中可以相对于彼此的约束位置放置子视图。 我们将在以后的教程中详细介绍它。

TextView is a view that displays a string.

TextView是显示字符串的视图。

The above XML is displayed in the text editor of the layout file.
We can also view and arrange our UI from the design editor that’s given below.

以上XML显示在布局文件的文本编辑器中。
我们还可以通过下面提供的设计编辑器查看和安排UI。

We’ve added a button to the above layout by dragging it from the sidebar. We’ve fixed the constraints such that it is positioned below the TextView. Don’t worry if these things are going over your head right now. We’ll cover each of these stuff separately in our later tutorials.

我们已经通过从边栏拖动按钮在上述布局中添加了按钮。 我们已经修复了约束,使其位于TextView下方。 不用担心这些事情现在是否已经过去了。 我们将在以后的教程中分别介绍这些内容。

Let’s look at the MainActivity.kt file as shown below.

让我们看一下MainActivity.kt文件,如下所示。

package net.androidly.helloworldkotlin

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

In Kotlin classes are public and final by default, so specifying the keyword class would suffice.

在Kotlin中,默认情况下,类是public和final的,因此指定关键字class就足够了。

Note: To specify a class as not final we need to mention it as open.

注意:要将一个类指定为非最终类,我们需要将其称为开放类。

Unlike Java, Kotlin doesn’t have an extends keyword. A colon is used instead.

与Java不同,Kotlin没有extends关键字。 取而代之的是冒号。

AppCompatActivity is derived from the Activity class and it supports backward compatibility.

AppCompatActivity派生自Activity类,它支持向后兼容。

This allows the current code to work on devices with older Android devices.

这样,当前代码就可以在装有旧版Android设备的设备上运行。

AppCompatActivity enables the use of ActionBar and other Material Design specific implementations like the Toolbar etc.

AppCompatActivity允许使用ActionBar和其他特定于Material Design的实现,例如工具栏等。

In Kotlin a function is defined using the keyword fun.

在Kotlin中,使用关键字fun定义函数。

The onCreate function is where the Activity loads onto the screen and displays the layout by invoking the function setContentView with the layout file.

活动将加载到屏幕上并通过使用布局文件调用功能setContentView来显示布局的onCreate函数。

Note: R.java file is an auto-generated file that contains resource IDs for all the resources present in the res folder.

注意:R.java文件是一个自动生成的文件,其中包含res文件夹中所有资源的资源ID。

将视图从布局链接到活动 (Linking Views From Layout to Activity)

Did you notice we’d set an id to our TextView and Button present in the activity_main.xml layout file?
We’ll use the very same to access them in our Kotlin Activity class.

您是否注意到我们会为activity_main.xml布局文件中存在的TextView和Button设置一个ID?
我们将在Kotlin Activity类中使用相同的内容访问它们。

Unlike Activities in Java, Kotlin Activity class does not require a findViewById method to bind the views in the activity. To access the layout elements in the Kotlin activity we need to add the following import line at the top:

与Java中的Activity不同,Kotlin Activity类不需要findViewById方法来绑定Activity中的视图。 要访问Kotlin活动中的布局元素,我们需要在顶部添加以下导入行:

import kotlinx.android.synthetic.main.activity_main.*

We’ve added a feature that changes the text present in the TextView when the Button is clicked as shown below:

我们添加了一项功能,可在单击按钮时更改TextView中显示的文本,如下所示:

package net.androidly.helloworldkotlin

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button.setOnClickListener { textView.setText("Hello World With Kotlin") }
    }
}

This looks a lot cleaner, concise than its Java Equivalent as shown below:

与Java等效项相比,这看起来更加简洁明了:

public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = findViewById(R.id.textView);
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setText("Hello World with Kotlin is better");
            }
        });
    }
}

In the Kotlin code, there’s no need to declare the views or override the onClick method interface. Furthermore, no semicolons required!

在Kotlin代码中,无需声明视图或重写onClick方法接口。 此外,不需要分号!

运行我们的Hello World应用程序 (Running Our Hello World App)

We can either run the application on a USB connected device or on an emulator. Click on the run button from the toolbar and you’ll be shown a window to choose the device you wish to run on:

适用于初学者的Android Hello World Kotlin应用程序

我们可以在USB连接的设备或仿真器上运行该应用程序。 单击工具栏上的运行按钮,将显示一个窗口,供您选择要在其上运行的设备:

Create a Virtual Device if you haven’t. Once it’s ready the project would build and run on your device.
Following is the output of our application when running on a device.

适用于初学者的Android Hello World Kotlin应用程序

如果尚未创建,请创建一个虚拟设备。 准备就绪后,项目将在您的设备上构建并运行。
以下是在设备上运行时应用程序的输出。

To enable USB Debugging on your smartphone:
Settings > About Phone.
Tab Build Number 7 times to activate Developer mode.
You’ll be able to find Developer Options in your settings. Go ahead and enable USB debugging from there.

要在智能手机上启用USB调试,请执行以下操作:
设置>关于手机。
选项卡内部编号7次以**开发人员模式。
您将可以在设置中找到“开发人员选项”。 继续并从那里启用USB调试。

This brings an end to this tutorial. You can download the Android Hello World Kotlin Project from the link below.
Stay tuned as we have lots to cover in our Android Development with Kotlin series.

本教程到此结束。 您可以从下面的链接下载Android Hello World Kotlin项目。
请继续关注,因为我们有很多要介绍的Kotlin Android开发系列。

翻译自: https://www.journaldev.com/34/android-hello-world-kotlin