安卓开发教程21:初识 Activity (下)

120 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第21天,点击查看活动详情

前面我们说了 Activity 的创建、启动、结束,以及 Activity 的生命周期。今天让我们来介绍的也是必须要掌握的,是在开发中必然会用到的,Activity 与 Activity 之间的传值。

我们在开发中会经常遇到的一个情况就是,用户在 A 页面点击一个按钮 跳转到了 B 页面,在 B 页面中进行一些操作,但是在操作过程中必须要用的到 A 页面中的数据。那么这个时候就需要,从 A 跳转到 B 的时候 携带着数据 到 中期B。那么在 Android 中我们用 Intent 来对各个组件之间进行通讯连接。

Intent

在前一篇文章中我们已经使用了 Intent,就在打开一个 Activity 的时候 startActivity 方法中我们 new 了一个 Intent。那么Intent 到底是什么意思呢?从字面翻译来看是 “ 意图 ” 的意思,简单理解就是 你想要干什么,比如我们 用 startActivity()打开页面的时候要用 Intent 从 this(A页面) 打开 B页面。

回到上面的需求上来,如果我们想 从 A页面 打开 B页面 的时候 带参数一起过去,就需要用到 Intent 就给我们提供了方法了,下面我们先来了解一下 Intent 的结构。

属性说明
component目标组件的名称
action想要执行的动作
data具体的数据
category在执行动作的类别
type指定的数据类型
extras附件信息

下面我们来用一个例子来看一下 Intent 是怎么使用的:

传递数据

示例:
  1. 从 A页面(携带参数) 打开 B页面
  2. B页面 接收 A页面的参数 显示出来
代码:

从简单的打开页面:

        startActivity(new Intent(this, PageBb.class));

变成了中间携带参数的:


        Intent intent = new Intent(this, PageBb.class);

        intent.putExtra("cont","我是从A来的数据");

        startActivity(intent);

在 页面 B 接收参数 的方法:

    Bundle formA =  getIntent().getExtras();
    String fromAcont = formA.getString("cont");
    

如果有多条数据需求携带到 B页面,可以使用 Bundle :


        Intent intent = new Intent(this, PageBb.class);

        Bundle bundle = new Bundle();
        bundle.putString("title","标题1");
        bundle.putString("cont","我是从A来的数据");
        intent.putExtras(bundle);

        startActivity(intent);

在 B页面 接收:

   Bundle formA =  getIntent().getExtras();
   
   String fromAcont = formA.getString("cont");
   String fromAcont = formA.getString("title");
   

返回数据

示例:
  1. 从 A页面(携带参数) 打开 B页面
  2. B页面 接收 A页面的参数 显示出来
  3. 从 B页面 返回参数给 A页面
  4. A页面 接收 B页面返回的参数 显示出来
代码:

首先修改 A页面, 用 registerForActivityResult 的方法发送参数和接收返回的参数


protected void onCreate(Bundle savedInstanceState) {

    resgiter = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            //判断返回状态
            if(result.getResultCode() == Activity.RESULT_OK){
                //接收返回参数并显示
            }
        }
    });
}


public void onClick(View view) {

        Intent intent = new Intent(this, PageBb.class);
        Bundle bundle = new Bundle();
        bundle.putString("title","标题1");
        bundle.putString("cont","我是从A来的数据");
        intent.putExtras(bundle);

        //用 registerForActivityResult 方式发送数据打开B页面
        resgiter.launch(intent);

    }

在 B页面 用 setResult 方法返回参数

    Intent intent = new Intent(this, PageAa.class);
    Bundle bundle = new Bundle();
    bundle.putString("title","标题2");
    bundle.putString("cont","我是从B返回的数据");
    intent.putExtras(bundle);

    setResult(Activity.RESULT_OK, intent);

今天我们简单的介绍了一下 Android 中 Intent 在 Activaty 中传递参数的方法,还有一些用法没有介绍,会在以后使用到的时候再做介绍。