Android中实现两个Activity之间的数据传递的实现和总结

Android中实现两个Activity之间的数据传递的实现和总结

在 Android 开发中,实现两个 Activity 之间传递文本数据是非常基础且常见的需求。下面我将详细介绍如何通过 Intent 实现从一个 Activity 传递数据到第二个 Activity。

一、实现原理

Android 中 Activity 之间的数据传递主要通过Intent来完成,核心步骤包括:

在发送方 Activity 中,通过 Intent 的putExtra()方法添加要传递的数据。在接收方 Activity 中,通过getIntent()获取传递过来的 Intent,再用getStringExtra()获取文本数

二、具体实现步骤

创建两个Activity。
MainActivity

package com.example.datatransfer;

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

public class MainActivity extends AppCompatActivity {
    private Button sendButton;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        sendButton = findViewById(R.id.btn_send);
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                intent.putExtra("KEY_MESSAGE", "你好");
                startActivity(intent);
            }
        });
    }
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">
    
    <Button
        android:id="@+id/btn_send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="发送数据"
        android:textSize="18sp"
        android:padding="16dp" />
</LinearLayout>

SecondActivity

package com.example.datatransfer;

import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class SecondActivity extends AppCompatActivity {
    private TextView messageTextView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        
        messageTextView = findViewById(R.id.tv_message);
        Intent intent = getIntent();
        
        if (intent != null && intent.hasExtra("KEY_MESSAGE")) {
            String message = intent.getStringExtra("KEY_MESSAGE");
            messageTextView.setText("接收到的信息:" + message);
        } else {
            messageTextView.setText("未接收到数据");
        }
    }
}

activity_second.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="16dp">

    <TextView
        android:id="@+id/message_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:textStyle="bold" />
</LinearLayout>

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.datatransfer">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SecondActivity"
            android:label="接收数据">
        </activity>
    </application>

</manifest>
三、关键代码解析
  1. 数据传递的核心方法
    • intent.putExtra("KEY_MESSAGE", message):第一个参数是键(自定义字符串),第二个是要传递的值
    • intent.getStringExtra("KEY_MESSAGE"):通过相同的键获取传递过来的值
  2. 注意事项
    • 键名(如 “KEY_MESSAGE”)需要在发送方和接收方保持一致
    • 接收数据前建议使用hasExtra()检查是否存在该键,避免空指针异常
    • 对于简单文本数据,使用getStringExtra();如果是其他类型数据,需使用对应的获取方法(如getIntExtra()
四、扩展:传递复杂数据

如果需要传递自定义对象,可通过以下方式

  1. 让对象实现Serializable接口
  2. 或让对象实现Parcelable接口(性能更好)

例如传递一个 Person 对象:

// 发送方
Intent intent = new Intent(...);
intent.putExtra("KEY_PERSON", new Person("张三", 20));
startActivity(intent);

// 接收方
Person person = (Person) intent.getSerializableExtra("KEY_PERSON");

通过以上步骤,你就完成了两个 Activity 之间文本数据 “你好” 的传递。这种方式是 Android 开发中最基础的数据传递方式,适用于大多数简单数据传递场景。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值