Frontend/실습

167. [AI][Android Studio] 로직개발하기 : 다중페이지 개발(Activity Lifecycle)

천재단미 2025. 3. 5. 17:31
728x90
반응형

 

 

 

 

 

 

 

안드로이드 앱을 개발하다 보면 여러 화면 간의 데이터 전달이 필요한 상황이 자주 발생합니다. 예를 들어, 첫 번째 화면에서 이름과 나이를 입력하고, 두 번째 화면에서 그 정보를 출력하는 UI를 구성해야 할 때가 있죠.

이번 포스팅에서는 EditText, Button을 이용한 사용자 입력 → SharedPreferences 저장 → 액티비티 전환 → 데이터 전달 → 출력까지의 다중 페이지 구성 로직을 Android Studio에서 직접 구현한 예제를 통해 설명합니다.


1. XML 레이아웃 구성

1-1. MainActivity

  • EditText

<?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"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <EditText
        android:id="@+id/editName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="이름"
        android:inputType="text"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="16dp"/>

    <EditText
        android:id="@+id/editAge"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="나이"
        android:inputType="number"
        app:layout_constraintTop_toBottomOf="@id/editName"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="16dp"/>

 

 

  • EditText

 

 

  • Button-1 

    <Button
        android:id="@+id/btnSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="저장"
        app:layout_constraintTop_toBottomOf="@id/editAge"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="32dp"/>

 

  • Button-2

    <Button
        android:id="@+id/btnOpenSecond"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Open Second Activity"
        app:layout_constraintTop_toBottomOf="@id/btnSave"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="16dp"/>

 

 

 

activity_main.xml에서 이름과 나이를 입력받는 EditText 2개와 버튼 2개(저장, 화면 전환)를 배치했습니다.

✔️ ConstraintLayout으로 상하 연결을 설정해 UI가 순서대로 배치되도록 구성했습니다.

EditText의 너비는 0dp, 제약조건(constraintStart, constraintEnd)으로 부모 기준 정렬되며 wrap_content로 높이 조정됨

Button도 마찬가지로 상단 위젯 기준 Top_toBottomOf 제약조건으로 배치

 

 

1-2. activity_second

<?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:orientation="vertical"
    android:gravity="center_horizontal"
    android:padding="16dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:text="두번째 화면"
        android:gravity="center"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/txtName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:layout_marginBottom="8dp"/>

    <TextView
        android:id="@+id/txtAge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"/>

</LinearLayout>

 

이미지 중심 UI 구성 시에는 다음과 같이 설정할 수 있습니다.

  • ImageView 설정
    • layout_width="300dp", layout_height="200dp"
    • scaleType="centerCrop"
    • ConstraintLayout으로 중앙 정렬
  • Button
    • 아래쪽 마진 layout_marginTop="20dp"
    • layout_constraintBottom_toBottomOf="parent"로 하단 고정
    • app:layout_constraintHorizontal_bias="0.7" 등으로 위치 조정 가능

 


2. MainActivity에서 데이터 저장 및 화면 전환

btnSave.setOnClickListener(v -> saveData());
btnOpenSecond.setOnClickListener(v -> openSecondActivity());

 

  • saveData()에서는 이름/나이 값을 SharedPreferences에 저장
  • openSecondActivity()에서는 입력된 데이터를 Intent로 넘겨 두 번째 액티비티를 실행합니다.
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("name", name);
intent.putExtra("age", Integer.parseInt(ageStr));
startActivity(intent);

 

SharedPreferences는 앱을 껐다 켜도 데이터가 남아있도록 할 수 있어 사용자 경험을 개선하는 데 유용합니다.

 

package com.mybea1109.lifecycle;

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

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    // UI 요소 선언
    EditText editName;
    EditText editAge;
    Button btnSave;
    Button btnOpenSecond;

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

        // UI 요소 초기화
        editName = findViewById(R.id.editName);
        editAge = findViewById(R.id.editAge);
        btnSave = findViewById(R.id.btnSave);
        btnOpenSecond = findViewById(R.id.btnOpenSecond);

        // 저장 버튼 클릭 리스너 설정
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
            }
        });

        // 두 번째 액티비티 열기 버튼 클릭 리스너 설정
        btnOpenSecond.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openSecondActivity();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }

    private void saveData() {
        // 이름과 나이를 받아온다.
        String name = editName.getText().toString();
        String ageStr = editAge.getText().toString();

        // 입력값 검증
        if (name.isEmpty() || ageStr.isEmpty()) {
            Toast.makeText(this, "이름과 나이를 모두 입력해주세요.", Toast.LENGTH_SHORT).show();
            return;
        }

        int age = Integer.parseInt(ageStr);

        // SharedPreferences에 데이터 저장
        SharedPreferences sharedPreferences = getSharedPreferences("UserData", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("name", name);
        editor.putInt("age", age);
        editor.apply();

        // 저장 완료 메시지 표시
        Toast.makeText(this, "저장되었습니다.", Toast.LENGTH_SHORT).show();
    }

    private void loadData() {
        // SharedPreferences에서 데이터 불러오기
        SharedPreferences sharedPreferences = getSharedPreferences("UserData", MODE_PRIVATE);
        String name = sharedPreferences.getString("name", "");
        int age = sharedPreferences.getInt("age", 0);

        // UI에 불러온 데이터 표시
        editName.setText(name);
        if (age != 0) {
            editAge.setText(String.valueOf(age));
        }
    }

    private void openSecondActivity() {
        // 액티비티를 띄울때는 Intent를 사용한다.
        Intent intent = new Intent(this, SecondActivity.class);
        String name = editName.getText().toString();
        String ageStr = editAge.getText().toString();
        if (!name.isEmpty() && !ageStr.isEmpty()) {
            intent.putExtra("name", name);
            intent.putExtra("age", Integer.parseInt(ageStr));
        }
        startActivity(intent);
    }
}

3. SecondActivity에서 데이터 수신 및 출력

String name = getIntent().getStringExtra("name");
int age = getIntent().getIntExtra("age", -1);
txtName.setText("이름은 : " + name + "입니다.");
txtAge.setText("나이는 " + age + "세 입니다.");

 

activity_second.xml에는 TextView 2개를 선언해 MainActivity에서 넘어온 데이터를 표시합니다.

 


4. 생명주기 로그 확인 (Logcat)

SecondActivity에 다음과 같은 생명주기 콜백 로그를 추가하여 전환 시 Activity의 상태 흐름을 추적할 수 있습니다.

@Override
protected void onStart() {
    super.onStart();
    Log.i("Myapp", "SecondActivity : start");
}

 

package com.mybea1109.lifecycle;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class SecondActivity extends AppCompatActivity {

    String TAG = "SecondActivity";
    TextView txtName;
    TextView txtAge;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        Log.i("Myapp", "SecondActivity : create");

        txtName = findViewById(R.id.txtName);
        txtAge = findViewById(R.id.txtAge);

        // Intent에서 데이터 받아오기
        String name = getIntent().getStringExtra("name");
        int age = getIntent().getIntExtra("age", -1);

        // 받아온 데이터 화면에 표시
        txtName.setText(String.format("이름은 : %s 입니다.", name));
        txtAge.setText(age != -1 ? String.format("나이는 %d세 입니다.", age) : "나이 정보가 없습니다.");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i("Myapp", "SecondActivity : start");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i("Myapp", "SecondActivity : resume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i("Myapp", "SecondActivity : pause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i("Myapp", "SecondActivity : stop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("Myapp", "SecondActivity : destroy");
    }
}

5. 전체 파일 구조 정리

  • activity_main.xml: EditText 2개 + 저장/전환 버튼
  • activity_second.xml: TextView 2개
  • MainActivity.java: 입력값 저장, 액티비티 전환
  • SecondActivity.java: 전달값 수신, 출력
  • AndroidManifest.xml: 두 액티비티 등록

6. 예시 시나리오

  • 이름입력
  • 나이입력
  • 저장버튼 클릭
  • SecondActivity 클릭

 

 

 

 

마무리

이 예제를 통해 하나의 액티비티에서 데이터를 입력하고, 다른 액티비티에서 출력하는 전 과정을 직접 코딩하고 XML로 레이아웃을 배치하며 구현할 수 있습니다. Android 개발에 입문했다면 반드시 숙지해야 할 내용입니다.

728x90
반응형
home top bottom
}