目录
5、使用 Intent 在 Activity 之间穿梭
Intent:Android程序中各组件之间进行交互的一种重要方式,它不仅可以指明当前组件想要执行的动作,还可以在不同的组件传递数据。Intent一般用于启动Activity,启动Service以及发送广播等场景。Intent有多个构造函数的重载。Intent大致可以分为两种:显示Intent和隐式Intent。
(1)使用显式 Intent
① 右击com.example.activitytest包 -> New -> Activity -> Empty Activity -> 命名SecondActivity -> 勾选Generate Layout File -> 给布局文件命名,但不要勾选Launcher Activity选项
② 修改布局文件 activity_second.xml 中的代码,定义一个按钮
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 2" />
</LinearLayout>
③ 任何一个 Activity 都是需要在 AndroidMainfest.xml 中注册的,打开 AndroidMainfest.xml ,Android Studio 已经帮我们自动完成了。因为 SecondActivity 不是主 Activity,因此不需要配置<intent-filter>标签里的内容。
<activity
android:name=".SecondActivity"
android:exported="false" />
<activity
android:name=".MainActivity"
android:exported="true"
android:label="This is MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
SecondActivity自动添加代码,在Activity加载布局,SetContentView(R.layout.activity_second),AndroidMainfest.xml自动注册布局。
④ 修改 SecondActivity中按钮的点击事件,点击按钮就会跳转到 SecondActivity
button1.setOnClickListener {
Toast.makeText(this,"You clicked Button 1",Toast.LENGTH_SHORT).show()
// 显式Intent
//第一个参数:启动Activity的上下文
//第二个参数,指定想要启动的目标Activity
val intent = Intent(this,SecondActivity::class.java)
startActivity(intent)
}
⑤ 运行,点击 Button 1,跳转到 SecondActivity,按一下 Back 键就可以销毁当前 Activity,从而回到上一个 Activity。
(2)使用隐式Intent
它并不明确指出想要启动哪一个Activity,而是指定了一系列更为抽象的action和category等信息,然后交由系统去分析这个Intent,并且班我