You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发:如何每10秒展示字符串数组中的随机单词?

实现每10秒随机展示单词的方案

别客气呀!刚学Android遇到这类小需求太正常了,我来给你两种简单易懂的实现方式,你可以选自己顺手的来~

先假设你的单词数组大概是这样的(可替换成你自己的内容)

val wordArray = arrayOf("Apple", "Banana", "Orange", "Grape", "Mango")

方法一:用Handler+Runnable(传统入门友好版)

这种方式逻辑直观,适合刚入门理解定时任务的原理:

  1. 定义Handler和Runnable,在Runnable里完成随机选单词和更新UI的操作,再通过postDelayed让它10秒后再次执行,形成循环;
  2. 记得在页面销毁时移除回调,避免内存泄漏。

完整代码示例:

class MainActivity : AppCompatActivity() {
    private lateinit var wordTextView: TextView // 用来展示单词的TextView
    private val wordArray = arrayOf("Apple", "Banana", "Orange", "Grape", "Mango")
    private val handler = Handler(Looper.getMainLooper())
    private lateinit var updateWordRunnable: Runnable

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        wordTextView = findViewById(R.id.wordTextView) // 绑定布局里的TextView

        // 初始化定时任务逻辑
        updateWordRunnable = Runnable {
            // 生成随机索引,范围是0到数组长度-1
            val randomIndex = Random().nextInt(wordArray.size)
            val randomWord = wordArray[randomIndex]
            // 更新UI展示单词
            wordTextView.text = randomWord
            // 10秒后再次执行这个Runnable(10000毫秒=10秒)
            handler.postDelayed(updateWordRunnable, 10000)
        }

        // 启动第一次展示
        handler.post(updateWordRunnable)
    }

    override fun onDestroy() {
        super.onDestroy()
        // 页面销毁时移除任务,防止内存泄漏
        handler.removeCallbacks(updateWordRunnable)
    }
}

方法二:用协程(现代简洁版)

这是Jetpack推荐的方式,代码更简洁,还不用手动处理内存泄漏(协程会跟随页面生命周期自动取消):

  1. 确保你的项目已经引入协程依赖(新建Android项目一般默认包含);
  2. 用lifecycleScope.launch启动协程,在循环里完成随机选单词、更新UI,然后用delay等待10秒。

完整代码示例:

class MainActivity : AppCompatActivity() {
    private lateinit var wordTextView: TextView
    private val wordArray = arrayOf("Apple", "Banana", "Orange", "Grape", "Mango")

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

        // 启动协程执行定时任务
        lifecycleScope.launch {
            while (true) {
                // 随机挑选单词
                val randomIndex = Random().nextInt(wordArray.size)
                val randomWord = wordArray[randomIndex]
                // 直接更新UI(lifecycleScope的协程默认在主线程)
                wordTextView.text = randomWord
                // 等待10秒再执行下一次
                delay(10000)
            }
        }
    }
}

几个关键注意点

  • 随机索引的正确性:Random().nextInt(wordArray.size)会生成0到wordArray.size-1的整数,刚好对应数组的有效索引,不会越界;
  • UI更新必须在主线程:上面两种方式都是在主线程执行UI更新,不用额外切换线程;
  • 生命周期管理:Handler要在onDestroy移除回调,协程用lifecycleScope的话会自动跟随页面销毁而取消,不用担心内存泄漏。

内容的提问来源于stack exchange,提问作者johannpc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:24:45