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

Kotlin实现点击按钮跳转后在SecondActivity显示按钮ID与时间戳

问题修复方案

1. 修改第一个Activity的按钮点击处理逻辑

你当前的代码没有把按钮ID和时间戳通过Intent传递给SecondActivity,这是无法显示数据的核心原因。需要在buttonPressed方法中添加数据传递逻辑:

private fun buttonPressed(button: Button) {
    val format = SimpleDateFormat("dd/MM/yyyy HH:mm aa", Locale.getDefault())
    val timestamp = format.format(Date())
    val intent = Intent(this, SecondActivity::class.java)
    // 传递按钮ID
    intent.putExtra("buttonId", button.id)
    // 传递时间戳
    intent.putExtra("timestamp", timestamp)
    startActivity(intent)
}

建议给SimpleDateFormat指定Locale,避免不同地区的时间格式显示差异

2. 修改SecondActivity的数据获取逻辑

你当前获取buttonId时用了未初始化的变量作为默认值,会导致编译错误,需要替换为合理的默认值(比如-1),同时增加空值判断避免时间戳为空时显示异常:

val textView_buttonPressed: TextView = findViewById(R.id.textView_buttonPressed)
val event_buttonPressed: TextView = findViewById(R.id.event_buttonPressed)
// 用-1作为默认值,代表未获取到有效按钮ID
val buttonId = intent.getIntExtra("buttonId", -1)
val timestamp = intent.getStringExtra("timestamp")

textView_buttonPressed.text = "Button Id: $buttonId"
event_buttonPressed.text = "Timestamp: ${timestamp ?: "未获取到时间"}"

可选优化:简化按钮绑定代码

你可以用批量绑定的方式减少重复代码:

// 批量获取按钮并绑定点击事件
val buttons = listOf<Button>(
    findViewById(R.id.button_one),
    findViewById(R.id.button_two),
    findViewById(R.id.button_three),
    findViewById(R.id.button_four)
)
buttons.forEach { button ->
    button.setOnClickListener { buttonPressed(button) }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 01:04:55