Android应用开发:Activity(2)

目录

5、使用 Intent 在 Activity 之间穿梭

(1)使用显式 Intent

(2)使用隐式Intent

(3)更多隐式 Intent 的用法

(4)向下一个 Activity 传递数据

(5)返回数据给上一个 Activity


5、使用 Intent 在 Activity 之间穿梭

        IntentAndroid程序中各组件之间进行交互的一种重要方式,它不仅可以指明当前组件想要执行的动作,还可以在不同的组件传递数据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,并且班我

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值