【Android】使用intent传递数据

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/sandalphon4869/article/details/100070609


一、传递数据

要传递信息的Activity

用到Intent提供的putExtra()方法

  • 第一个参数是键,用于要接收信息的Activity从Intent中取值。
  • 第二个参数是数据。
Intent intent=new Intent(MissionActivity.this,MainActivity.class);
intent.putExtra("sg","simple");
startActivity(intent);

要接收信息的Activity

getIntent()方法获取到要传递信息的Activity的Intent。
获得键值用getStringExtra():String类型用getStringExtra(),Int类型用getIntExtra(),Boolean用getBooleanExtra()。

Intent intent = getIntent();
String sg=intent.getStringExtra("sg");

二、回传数据

1.发出请求信息并接收回答的Activity

启动intent发出请求

不使用startActivity()启动活动,而是使用startActivityForResult()启动活动:

  • 第一个参数是intent
  • 第二个参数是requestCode值。用这个参数来判断是从哪个activity中返回的
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
startActivityForResult(intent,1);

接受回答

在填写回答的Activity被销毁后调用onActivityResult()方法来接受数据。

先判断requestCode是从哪个activity中返回的,再判断resultCode目标Activity处理信息的不同的结果,resultCode是指这个活动返回的数据的序号,一个活动可能传回多个数据结果。

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
	//判断是从哪个activity中返回的
    if(requestCode==1)
    {
    	//目标Activity处理信息的不同的结果:成功、失败、还是怎么了。
        if(resultCode==RESULT_OK)
        {
            String sg=data.getStringExtra("sg");
        }
    }
}

2.填写回答的Activity

(1)核心代码

Intent intent=new Intent();
intent.putExtra("sg","simple");
setResult(RESULT_OK,intent);
finish();

setResult(int resultCode,Intent data)专门用来向上一个活动返回数据:

  • resultCode:表示处理结果的标识值,一般用RESULT_OKRESULT_CANCELED
  • data:是intent

setResult()只能用来传回数据,但页面不会跳转,所以得用finish()销毁填写回答的Activity,跳转并让接收回答的Activity接受数据。

(2)调用方式

按钮式

button2= this.<Button>findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent=new Intent();
		intent.putExtra("sg","simple");
		setResult(RESULT_OK,intent);
		finish();
    }
});

Back键返回

@Override
public void onBackPressed() {
    Intent intent=new Intent();
	intent.putExtra("sg","simple");
	setResult(RESULT_OK,intent);
	finish();
}
//super.onBackPressed();一定要删除,不然失败,不会执行下面的Intent代码

三、例子

在这里插入图片描述

发出请求的MainActivity

package com.example.hello;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private Button btn1;
    private Button btn2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn1=findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this,Main2Activity.class);
                startActivityForResult(intent,1);
            }
        });

        btn2=findViewById(R.id.btn2);
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this,Main3Activity.class);
                startActivityForResult(intent,2);
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //判断是从哪个activity中返回的
        switch (requestCode)
        {
            case 1:
            {
                //目标Activity处理信息的不同的结果:成功、失败、还是怎么了。
                if(resultCode==RESULT_OK)
                {
                    String sg=data.getStringExtra("sg");
                    Toast.makeText(MainActivity.this,sg,Toast.LENGTH_SHORT).show();
                }
                else if(resultCode==RESULT_CANCELED)
                {
                    String sg=data.getStringExtra("sg");
                    Toast.makeText(MainActivity.this,sg,Toast.LENGTH_SHORT).show();
                }
                break;
            }
            case 2:
            {
                if(resultCode==RESULT_OK)
                {
                    String sg=data.getStringExtra("sg");
                    Toast.makeText(MainActivity.this,sg,Toast.LENGTH_SHORT).show();
                }
                break;
            }
        }
    }
}

对应XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn1"
        android:text="To Main2"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn2"
        android:text="Tp Main3"/>
</LinearLayout>

传回不同答案的Main2Activity

package com.example.hello;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Main2Activity extends AppCompatActivity {

    private Button btn1;
    private Button btn2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        btn1=findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent();
                intent.putExtra("sg","OK");
                setResult(RESULT_OK,intent);
                finish();
            }
        });

        btn2=findViewById(R.id.btn2);
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent();
                intent.putExtra("sg","CANCELED");
                setResult(RESULT_CANCELED,intent);
                finish();
            }
        });
    }
}

对应XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Main2Activity"
    android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn1"
        android:text="Back Ok"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn2"
        android:text="Back CANCELED"/>

</LinearLayout>

验证requestCode的Main3Activity

package com.example.hello;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Main3Activity extends AppCompatActivity {

    private Button btn1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);

        btn1=findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent();
                intent.putExtra("sg","Main3");
                setResult(RESULT_OK,intent);
                finish();
            }
        });
    }
}

对应XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Main3Activity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn1"
        android:text="Back"/>

</androidx.constraintlayout.widget.ConstraintLayout>

猜你喜欢

转载自blog.csdn.net/sandalphon4869/article/details/100070609