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

Android Studio中Java实现记忆游戏按钮2秒后重新启用的方法

Android Studio实现记忆游戏按钮延迟启用功能

核心思路

  1. 统计按钮点击次数,达到2次时禁用所有按钮
  2. 通过延迟任务,2秒后重新启用所有按钮并重置点击计数

具体实现步骤

1. 定义全局变量

在你的Activity类中添加两个全局变量:

// 统计点击的按钮数量
private int clickCount = 0;
// 存储所有按钮的列表(可选优化,避免重复findViewById)
private List<Button> buttonList = new ArrayList<>();

2. 初始化按钮列表(可选优化)

在onCreate()方法里提前加载所有按钮到列表,不用每次循环查找:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);
    
    // 初始化按钮列表并绑定点击事件
    for (int i = 0; i < 12; i++) {
        int resID = getResources().getIdentifier("btn" + i, "id", getPackageName());
        Button button = findViewById(resID);
        buttonList.add(button);
        button.setOnClickListener(v -> onButtonClick((Button) v));
    }
}

3. 按钮点击逻辑与延迟启用实现

这里提供两种常用的延迟实现方式:

方式一:使用Handler(传统Android方式)
private void onButtonClick(Button clickedButton) {
    clickCount++;
    // 执行你已实现的按钮文本变化逻辑
    clickedButton.setText("目标文本");

    if (clickCount == 2) {
        // 禁用所有按钮
        disableAllButtons();
        // 2秒后重新启用按钮并重置计数
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            enableAllButtons();
            clickCount = 0;
        }, 2000); // 2000毫秒=2秒
    }
}

// 禁用所有按钮的方法
private void disableAllButtons() {
    for (Button button : buttonList) {
        button.setEnabled(false);
    }
}

// 启用所有按钮的方法
private void enableAllButtons() {
    for (Button button : buttonList) {
        button.setEnabled(true);
    }
}
方式二:使用Coroutine(Android推荐的协程方式)

如果你的项目已引入Coroutine依赖(Android Studio新建项目默认包含),可以用更贴合生命周期的实现:

private void onButtonClick(Button clickedButton) {
    clickCount++;
    clickedButton.setText("目标文本");

    if (clickCount == 2) {
        disableAllButtons();
        // 利用lifecycleScope确保Activity销毁时自动取消任务
        lifecycleScope.launch {
            delay(2000); // 延迟2秒
            enableAllButtons();
            clickCount = 0;
        }
    }
}

关键注意点

  • 启用/禁用按钮属于UI操作,必须在主线程执行,上述两种方式均自动满足该要求
  • 提前存储按钮列表可避免重复调用findViewById,提升性能
  • 协程方式能自动适配Activity生命周期,避免内存泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 15:32:38