웹사이트 검색

Android 조각 수명 주기


오늘은 Android Fragment Lifecycle에 대해 알아보고 Android 애플리케이션에서 두 개의 Fragment로 구성된 단일 활동 클래스를 구현해 보겠습니다.

안드로이드 조각

조각 수명 주기

  1. onAttach() : 이 메서드는 onCreate() 이전에도 먼저 호출되어 프래그먼트가 활동에 연결되었음을 알려줍니다. 프래그먼트를 호스팅할 활동이 전달됩니다.
  2. onCreateView() : 프래그먼트가 처음으로 UI를 그릴 때가 되면 시스템이 이 콜백을 호출합니다. 프래그먼트에 대한 UI를 그리려면 프래그먼트 레이아웃의 루트인 이 메서드에서 View 구성 요소를 반환해야 합니다. 프래그먼트가 UI를 제공하지 않으면 null을 반환할 수 있습니다.
  3. onViewCreated() : onCreateView() 이후에 호출됩니다. 이는 onCreateView() 구현을 상속할 때 특히 유용하지만 ListFragment 및 어댑터 설정 시기와 같은 결과 뷰를 구성해야 합니다.
  4. onActivityCreated() : 액티비티의 onCreate()가 완료되었음을 나타내기 위해 onCreate() 및 onCreateView() 후에 호출됩니다. 활동의 onCreate() 작업 완료에 따라 달라지는 프래그먼트에서 초기화해야 하는 것이 있는 경우 해당 초기화 작업에 onActivityCreated()를 사용할 수 있습니다.
  5. onStart() : 프래그먼트가 표시되면 onStart() 메서드가 호출됩니다.
  6. onPause() : 시스템은 사용자가 프래그먼트를 떠난다는 첫 번째 표시로 이 메서드를 호출합니다. 일반적으로 현재 사용자 세션 이후에도 지속되어야 하는 모든 변경 사항을 커밋해야 하는 곳입니다.
  7. onStop() : onStop()을 호출하여 중지할 조각
  8. onDestroyView() : onDestroy() 전에 호출됩니다. 이는 UI를 설정하는 onCreateView()에 해당합니다. UI와 관련하여 정리해야 할 사항이 있는 경우 해당 논리를 onDestroyView()에 넣을 수 있습니다.
  9. onDestroy() : 프래그먼트 상태의 최종 정리를 수행하기 위해 onDestroy()가 호출되지만 Android 플랫폼에서 호출된다는 보장은 없습니다.
  10. onDetach(): onDestroy() 이후에 호출되어 프래그먼트가 호스팅 활동에서 분리되었음을 알립니다.

Android 조각 클래스

Honeycomb(API 11)에서 Android API에 프래그먼트가 추가되었습니다.

  1. android.app.Fragment : 모든 프래그먼트 정의의 기본 클래스
  2. android.app.FragmentManager : 활동 내부의 프래그먼트 객체와 상호작용하기 위한 클래스
  3. android.app.FragmentTransaction : 프래그먼트 작업의 원자 집합을 수행하기 위한 클래스\nGoogle에서 제공하는 호환성 패키지 라이브러리를 사용할 때 다음 클래스를 사용하여 구현합니다.

  • android.support.v4.app.FragmentActivity : 호환성 기반 프래그먼트(및 로더) 기능을 사용하는 모든 활동의 기본 클래스
  • android.support.v4.app.Fragment
  • android.support.v4.app.FragmentManager
  • android.support.v4.app.FragmentTransaction

안드로이드 프래그먼트 onCreateView()

구현을 위해 onCreateView()를 사용하는 샘플 조각은 다음과 같습니다.

public class SampleFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parentViewGroup,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_sample, parentViewGroup, false);
        return rootView;
    }
}

onCreateView() 메서드는 LayoutInflater, ViewGroup 및 Bundle을 매개변수로 가져옵니다. LayoutInflater는 레이아웃 XML 파일을 기반으로 View 인스턴스를 생성할 수 있는 컴포넌트입니다. 보시다시피 예제는 실제로 layout.inflate()를 호출하여 이를 수행합니다. inflate() 메서드는 레이아웃 XML 파일의 ID(R.layout 내), 프래그먼트의 View가 삽입될 상위 ViewGroup, 프래그먼트의 레이아웃 XML 파일에서 확장된 보기는 상위 ViewGroup에 삽입되어야 합니다. 이 경우 우리가 호출하는 일부 Android 코드에 의해 뷰가 다른 곳에서 부모 ViewGroup에 연결되기 때문에 false를 전달합니다. inflate()에 마지막 매개변수로 false를 전달하면 상위 ViewGroup이 부풀려진 View의 레이아웃 계산에 계속 사용되므로 null을 상위 ViewGroup으로 전달할 수 없습니다. onCreateView()의 ViewGroup 매개변수는 프래그먼트의 보기가 삽입될 상위 ViewGroup입니다. 이것은 프래그먼트를 "호스트\하는 활동 내부의 ViewGroup입니다. onCreateView()의 Bundle 매개변수는 활동에서와 같이 프래그먼트가 데이터를 저장할 수 있는 번들입니다.

안드로이드 프래그먼트 예제

Android 조각 예제 코드

MainActivityTextFragmentMenuFragment라는 두 조각을 보유합니다. 따라서 xml 레이아웃 activity_main.xml에서 프래그먼트를 정의하는 것으로 시작하겠습니다.

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:weightSum="1.0">

    <fragment
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        class="journaldev.com.fragments.fragments.MenuFragment"
        android:id="@+id/fragment"
        android:layout_weight="0.5"/>
    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="journaldev.com.fragments.fragments.TextFragment"
        android:id="@+id/fragment2"
        android:layout_weight="0.5"/>
</LinearLayout>

보시다시피 이 활동의 일부인 프래그먼트의 클래스 파일은 class="journaldev.com.fragments.fragments.TextFragment”로 정의됩니다. 프래그먼트 클래스와 해당 레이아웃은 아래 스니펫에 표시된 대로 정의됩니다.

package journaldev.com.fragments.fragments;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import journaldev.com.fragments.R;
public class TextFragment extends Fragment {
    TextView text,vers;

    @Override

    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.text_fragment, container, false);
        text= (TextView) view.findViewById(R.id.AndroidOs);
        vers= (TextView)view.findViewById(R.id.Version);


        return view;

    }
    public void change(String txt, String txt1){
        text.setText(txt);
        vers.setText(txt1);

    }
}

text_fragment.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:gravity="center"
    android:background="#5ba4e5"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="40px"
        android:textColor="#ffffff"
        android:layout_gravity="center"
        android:id="@+id/AndroidOs"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="#ffffff"
        android:textSize="30px"
        android:id="@+id/Version"/>

</LinearLayout>

TextFragment는 안드로이드 버전 이름과 번호를 포함하는 텍스트뷰로 구성됩니다.

package journaldev.com.fragments.fragments;

import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import journaldev.com.fragments.R;
public class MenuFragment extends ListFragment {
    String[] AndroidOS = new String[] { "Cupcake","Donut","Eclair","Froyo","Gingerbread","Honeycomb","Ice Cream SandWich","Jelly Bean","KitKat" };
    String[] Version = new String[]{"1.5","1.6","2.0-2.1","2.2","2.3","3.0-3.2","4.0","4.1-4.3","4.4"};
    @Override

    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
        View view =inflater.inflate(R.layout.list_fragment, container, false);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, AndroidOS);
        setListAdapter(adapter);

        return view;

    }
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        TextFragment txt = (TextFragment)getFragmentManager().findFragmentById(R.id.fragment2);
        txt.change(AndroidOS[position],"Version : "+Version[position]);
        getListView().setSelector(android.R.color.holo_blue_dark);
    }
}

list_fragment.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@android:id/list" />
</LinearLayout>

MenuFragment는 ListView를 표시합니다. 여기에서 볼 수 있듯이 ListView의 레이아웃은 이전 기사에서 ListView에 대해 만든 사용자 지정 레이아웃과 달리 기본적으로 simple_list_item_1입니다. MainActivity는 onCreate 메서드에서 setContentView를 호출합니다. 조각은 xml 파일에서 호출됩니다. 또는 아래 스니펫에 표시된 대로 FragmentManager를 사용하여 활동 클래스에서 프래그먼트를 추가할 수 있습니다.

getFragmentManager()
                  .beginTransaction()
                  .add(R.id.fragmentParentViewGroup, new MyFragment())
                  .commit();

여기서 id fragmentParentViewGroup은 아래 표시된 FrameLayout에 속합니다.

<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
             xmlns:tools="https://schemas.android.com/tools"
             android:id="@+id/fragmentParentViewGroup"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             tools:context=".MyActivity"
             tools:ignore="MergeRootFrame" />

Android Fragment 예제 앱

Android Fragment 프로젝트 다운로드