Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드에서 한 프래그먼트에서 다른 프래그먼트로 데이터 전송하는 방법

개요

이 튜토리얼은 안드로이드 앱에서 인터페이스(Interface) 패턴을 활용하여 한 프래그먼트(Fragment)에서 다른 프래그먼트로 데이터를 전송하는 방법을 단계별로 설명합니다. 탭 레이아웃과 뷰페이저(ViewPager)로 구성된 화면에서 첫 번째 프래그먼트에 입력한 메시지가 두 번째 프래그먼트로 전달되어 화면에 표시되는 예제입니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File ⇒ New Project를 선택한 후, 새 프로젝트를 만드는 데 필요한 모든 세부 정보를 입력하여 프로젝트를 생성합니다.

2단계 — activity_main.xml 레이아웃 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. CoordinatorLayout 안에 ViewPager와 TabLayout을 배치하여 탭 기반 화면을 구성합니다.

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="https://schemas.android.com/apk/res/android"
   xmlns:app="https://schemas.android.com/apk/res-auto"
   xmlns:tools="https://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <androidx.viewpager.widget.ViewPager
      android:id="@+id/viewPager"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      app:layout_behavior="@string/appbar_scrolling_view_behavior" />
   <com.google.android.material.appbar.AppBarLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:theme="@style/AppTheme">
   <com.google.android.material.tabs.TabLayout
      android:id="@+id/tabLayout"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      app:tabGravity="fill"
      app:tabMode="fixed" />
   </com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

3단계 — 두 개의 프래그먼트 레이아웃 및 클래스 작성

데이터를 보내는 역할을 하는 FragmentOne과 받아서 표시하는 FragmentTwo, 두 개의 프래그먼트를 만들고 아래와 같이 코드를 작성합니다.

FragmentOne.java

import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class FragmentOne extends Fragment {
   private SendMessage sendMessage;
   public FragmentOne() {
   }
   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
      return inflater.inflate(R.layout.fragment_fragment_one, container, false);
   }
   @Override
   public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
      super.onViewCreated(view, savedInstanceState);
      Button btnPassData = view.findViewById(R.id.btnPassData);
      final EditText inData = view.findViewById(R.id.passMessage);
      btnPassData.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            sendMessage.sendData(inData.getText().toString().trim());
         }
      });
   }
   interface SendMessage {
      void sendData(String message);
   }
   @Override
   public void onAttach(@NonNull Context context) {
      super.onAttach(context);
      try {
         sendMessage = (SendMessage) getActivity();
      }
     catch (ClassCastException e) {
         throw new ClassCastException("Error in retrieving data. Please try again");
      }
   }
}

fragment_fragment_one.xml

<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:fillViewport="true">
   <RelativeLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content">
   <EditText
      android:id="@+id/passMessage"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_above="@+id/btnPassData"
      android:layout_margin="16dp"
      android:hint="Enter here" />
   <Button
      android:id="@+id/btnPassData"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:text="PASS DATA TO FRAGMENT TWO" />
   </RelativeLayout>
</ScrollView>

FragmentTwo.java

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentTwo extends Fragment {
   private TextView textView;
   public FragmentTwo() {
   }
   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
      return inflater.inflate(R.layout.fragment_fragment_two, container, false);
   }
   @Override
   public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
      super.onViewCreated(view, savedInstanceState);
      textView = view.findViewById(R.id.txtData);
   }
   void displayReceivedData(String message) {
      textView.setText("Data received: " + message);
   }
}

fragment_fragment_two.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"
   tools:context=".FragmentTwo">
   <TextView
      android:id="@+id/txtData"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textSize="20sp"
      android:textStyle="bold"
      android:layout_centerInParent="true"
      android:text="No data received" />
</RelativeLayout>

4단계 — MainActivity.java 작성

src/MainActivity.java에 아래 코드를 추가합니다. 여기서 핵심은 액티비티가 FragmentOne.SendMessage 인터페이스를 구현한다는 점입니다. 프래그먼트 간 직접 통신 대신 액티비티를 중재자로 활용하여 데이터를 전달하며, ViewPager의 프래그먼트 태그(android:switcher:)를 이용해 두 번째 프래그먼트 인스턴스를 찾아 데이터를 표시합니다.

package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
public class MainActivity extends AppCompatActivity implements FragmentOne.SendMessage{
   TabLayout tabLayout;
   ViewPager viewPager;
   ViewPagerAdapter viewPagerAdapter;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      viewPager = findViewById(R.id.viewPager);
      viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
      viewPager.setAdapter(viewPagerAdapter);
      tabLayout = findViewById(R.id.tabLayout);
      tabLayout.setupWithViewPager(viewPager);
   }
   @Override
   public void sendData(String message) {
      String tag = "android:switcher:" + R.id.viewPager + ":" + 1;
      FragmentTwo f = (FragmentTwo) getSupportFragmentManager().findFragmentByTag(tag);
      f.displayReceivedData(message);
   }
}

5단계 — AndroidManifest.xml 확인

androidManifest.xml에 아래 코드를 추가합니다.

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

앱 실행하기

이제 애플리케이션을 실행해 결과를 확인해 보겠습니다. 실제 안드로이드 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바에서 Run(실행) 아이콘을 클릭하세요. 실행 옵션에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

안드로이드에서 한 프래그먼트에서 다른 프래그먼트로 데이터 전송하는 방법