如何在Android中设置延迟?
在某些情况下,我们需要一段时间后更新UI来解决这个问题。本例演示如何在Android中设置延迟。
步骤1 - 在Android Studio中创建一个新项目,转到文件⇒新建项目,并填写所有必需的详细信息以创建一个新项目。
步骤2 - 将以下代码添加到res/layout/activity_main.xml。
<?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:id = "@+id/parent" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:gravity = "center" android:orientation = "vertical"> <TextView android:id = "@+id/textChanger" android:layout_margin = "20dp" android:textAlignment = "center" android:text = "Initial text" android:layout_width = "match_parent" android:layout_height = "wrap_content" /> </LinearLayout>
在上面的代码中,我们使用了TextView,它最初显示“初始文本”,一段时间后将更新为新文本。
步骤3 - 将以下代码添加到src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int view = R.layout.activity_main;
TextView textChanger;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(view);
textChanger = findViewById(R.id.textChanger);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
textChanger.setText("After some delay, it changed to new text");
}
}, 5000);
}
}在上面的代码中,我们使用了Handler来维护延迟,如下所示:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
textChanger.setText("After some delay, it changed to new text");
}
}, 5000);在上面的代码中,5000毫秒后更新文本。让我们尝试运行您的应用程序。我假设您已将您的实际Android移动设备连接到您的计算机。要从Android Studio运行应用程序,请打开项目的其中一个活动文件,然后点击运行
工具栏中的图标。选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕:

最初,它将显示如上所示的文本。一段时间后,它将更新文本,如下所示:

点击此处下载项目代码
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP