Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách truyền dữ liệu giữa các Activity trong Android

Hướng dẫn này minh họa cách truyền dữ liệu đơn giản (String, int) giữa hai Activity bằng Intent và Bundle.

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project.

Bước 2: Giao diện màn hình 1 (res/layout/activity_first.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/activity_first"
    android:paddingTop="60dp"
    tools:context=".FirstActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="16dp">

        <EditText
            android:id="@+id/editTxtName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Nhập tên"
            android:ems="10" />

        <Spinner
            android:id="@+id/ageGroupSpinner"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp" />

        <Button
            android:id="@+id/btnSubmit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:layout_gravity="center_horizontal"
            android:text="Gửi" />

    </LinearLayout>
</RelativeLayout>

Bước 3: Giao diện màn hình 2 (res/layout/activity_second.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/activity_second"
    android:paddingTop="60dp">

    <TextView
        android:id="@+id/displayMsg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="20sp"
        android:layout_centerInParent="true" />

</RelativeLayout>

Bước 4: FirstActivity - Gửi (src/FirstActivity.java)

package com.example.sample;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class FirstActivity extends AppCompatActivity {
    private EditText editTxtName;
    private Spinner ageGroupSpinner;
    private Button btnSubmit;
    private int selectedAgeGroup = 0;

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

        editTxtName = findViewById(R.id.editTxtName);
        ageGroupSpinner = findViewById(R.id.ageGroupSpinner);
        btnSubmit = findViewById(R.id.btnSubmit);

        // Setup Spinner
        String[] ageGroups = {"Dưới 18", "18-30", "Trên 30"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, ageGroups);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        ageGroupSpinner.setAdapter(adapter);

        ageGroupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedAgeGroup = position;
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = editTxtName.getText().toString().trim();
                if (name.isEmpty()) {
                    Toast.makeText(FirstActivity.this, "Tên không được để trống!", Toast.LENGTH_LONG).show();
                    return;
                }

                Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("name", name);
                bundle.putInt("ageGroup", selectedAgeGroup);
                intent.putExtra("userBundle", bundle);
                startActivity(intent);
            }
        });
    }
}

Bước 5: SecondActivity - Nhận (src/SecondActivity.java)

package com.example.sample;

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

public class SecondActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        TextView displayMsg = findViewById(R.id.displayMsg);
        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra("userBundle");

        if (bundle != null) {
            String name = bundle.getString("name", "");
            int ageGroup = bundle.getInt("ageGroup", 0);

            String message = "Xin chào, " + name + "! ";
            switch (ageGroup) {
                case 0: message += "Hãy tận hưởng cuộc sống!"; break;
                case 1: message += "Đừng quá nghiêm trọng, hãy vui lên!"; break;
                case 2: message += "Hãy kỷ niệm những kỉ niệm đẹp!"; break;
            }
            displayMsg.setText(message);
        }
    }
}

Bước 6: Manifest (AndroidManifest.xml)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.sample">
    <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=".FirstActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SecondActivity" />
    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Nhập tên, chọn nhóm tuổi, nhấn "Gửi" để xem thông điệp tùy chỉnh trên màn hình 2.