如何在 Android Kotlin 中在延迟后调用方法?
此示例演示了如何在 Android Kotlin 中在延迟后调用方法。
步骤 1 − 在 Android Studio 中创建一个新项目,转到文件?新建项目并填写所有必需的详细信息来创建一个新项目。
步骤 2 − 将以下代码添加到 res/layout/activity_main.xml。
示例
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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:padding="16sp" tools:context=".MainActivity"> <TextView android:id="@+id/textViewTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:padding="8dp" android:text="Tutorials Point" android:textColor="@color/colorPrimaryDark" android:textSize="48sp" android:textStyle="bold" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/textViewTitle" android:layout_centerInParent="true" android:text="Wait for the Toast to display." android:textColor="@android:color/background_dark" android:textSize="24sp" android:textStyle="bold" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textColor="@android:color/holo_blue_dark" android:textSize="24sp" android:textStyle="bold" /> </RelativeLayout>
步骤 3 − 将以下代码添加到 src/MainActivity.kt
示例
import android.os.Bundle
import android.os.Handler
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var textView: TextView
private val string = "Delay by 5 seconds"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
textView = findViewById(R.id.textView)
val handler = Handler()
handler.postDelayed({ testToast() }, 5000)
}
private fun testToast() {
Toast.makeText(this, "This method is called after a delay!", Toast.LENGTH_SHORT).show()
textView.text = string
}
}步骤 4 − 将以下代码添加到 androidManifest.xml
示例
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.kotlipapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
让我们尝试运行你的应用程序。我假设你已将你的 Android 移动设备与计算机连接。要从 Android Studio 运行应用程序,请打开你项目的某个活动文件并单击工具栏中的运行图标
。选择你的移动设备作为选项,然后查看你的移动设备它会显示你的默认屏幕 −

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP