第 3 课2026.09.03
让页面中的按钮响应一次点击并修改提示文字。
第 3 课:Button与点击监听
- 日期:2026-09-03
- 课程序号:第 3 课
- 知识点:布局 ID、findViewById 与 setOnClickListener
用途
让页面中的按钮响应一次点击并修改提示文字。
核心概念
- 先 setContentView,再查找该布局中的控件;ID 用来定位控件,不是显示文案。
- 点击监听在事件发生时执行。本课仅改变界面提示,不代表执行了真实保存或网络业务。
最小代码或操作示例
xml
<!-- 替换 res/layout/activity_main.xml -->
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/start_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/start_lesson" />在 res/values/strings.xml 的 resources 中添加:
xml
<string name="start_lesson">开始练习</string>
<string name="lesson_started">已开始练习</string>在原 MainActivity 顶部添加 import android.widget.Button,并在 setContentView 后添加:
kotlin
val button = findViewById<Button>(R.id.start_button)
button.setOnClickListener {
button.setText(R.string.lesson_started)
}3~5 分钟练习
运行已有 Android 工程,确认初始文案和点击后文案不同;增加“准备复习”资源,并将点击后文案改成它。
参考答案
xml
<!-- resources 内增加 -->
<string name="review_ready">准备复习</string>
<!-- Kotlin 监听体改为 button.setText(R.string.review_ready) -->与上一课的联系
上一课显示 XML TextView 并使用字符串资源;本课换成可点击控件,通过 Activity 为它注册行为。