http://www.kmshack.kr/263


Fragment Lifecycle(생명주기)

Fragment의 가장 기본인 Lifecycle을 알아보자. 모든 것이든 기본이 가장 중요한만큼 하나하나 꼼꼼하게 분석 해보자. 

Fragment는 Activity와 비슷한 Lifecycle 구조를 가졌다.


(
2013/02/26 – [개발관련/Android] – Fragment 파헤치기 – 1. Fragment 개념)이전 Fragment 개념에 대해 간단히 언급 했듯이, Fragment는 Activity에서 작동하는 구조라고 소개 되었다.

하지만 Activity보다 좀더 복잡하지만, 개념만 이해 한다면 쉽게 사용 할것 이다.

FragmentTransaction으로 Fragment를 add, replace 한다. 이외 레이아웃에서 바로 add하는 경우도 있다.

이때 add, replace할때 부터 Lifecycle이 시작된다. 

- 최초 생성 Lifecycle

1. onAttach()

Fragment가 Activity에 붙을때 호출 된다.

2. onCreate()

Activity에서의 onCreate()와 비슷하나, ui관련 작업은 할 수 없다.

3. onCreateView()

Layout을 inflater을하여 View작업을 하는곳이다.

4. onActivityCreated()

Activity에서 Fragment를 모두 생성하고 난다음 호출 된다. Activity의 onCreate()에서 setContentView()한 다음이라고 생각 하면 쉽게 이해 될것 같다. 여기서 부터는 ui변경작업이 가능하다.

5. onStart()

Fragment가 화면에 표시될때 호출된다. 사용자의 Action과 상호 작용 할 수 없다.

6. onResume()

Fragment가 화면에 완전히 그렸으며, 사용자의 Action과 상호 작용이 가능하다.

- 다른 Fragment가 add

1. onPause()

Fragment가 사용자의 Action과 상호 작용을 중지한다.

2. onStop()

Fragment가 화면에서 더이상 보여지지 않게 되며, Fragment기능이 중지 되었을때 호출 된다.

3. onDestoryView()

View 리소스를 해제 할수 있도록 호출된다. 

backstack을 사용 했다면 Fragment를 다시 돌아 갈때 onCreateView()가 호출 된다.

- replace or backward로 removed되는 경우

4. onDestory()

Fragment상태를 완전히 종료 할 수 있도록 호출 한다.

5. onDetach()

Fragment가 Activity와 연결이 완전히 끊기기 직전에 호출 된다.

- 그외 Callbacks Method

onSaveInstanceState()

Activity와 동일하게 Fragment가 사라질떄 호출되며 상태를 Bundle로 저장할수 있도록 호출 된다. 

그럼 간단한 테스트 코드를 통해 Lifecycle에 맞게 작동 되는지 확인 해보도록 하자.


Activity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.test;
 
import com.example.fragmenttest.R;
 
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.AttributeSet;
import android.view.View;
 
public class FragmentTestActivity extends FragmentActivity {
    
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        setContentView(R.layout.main);
        
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        
        TestFragment newtf = TestFragment.newInstance(1);
        
        ft.replace(R.id.embedded, newtf);
        ft.commit();
        
    }
 
    @Override
    public void onAttachFragment(Fragment fragment) {
        super.onAttachFragment(fragment);
    }
    
    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        return super.onCreateView(name, context, attrs);
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }
    
}
 


Fragment

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package com.test;
 
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
 
import com.example.fragmenttest.R;
 
public class TestFragment extends Fragment {
    
    int mIdx;
     
    public static TestFragment newInstance(int index) {
        
        TestFragment fragment = new TestFragment();
        
        Bundle args = new Bundle();
        args.putInt("index", index);
        fragment.setArguments(args);
 
        return fragment;
    }
    
    
    @Override
    public void onAttach(Activity activity) {
        Log.d(this.getClass().getSimpleName(), "onAttach()");
        
        super.onAttach(activity);
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.d(this.getClass().getSimpleName(), "onCreate()");
        
        super.onCreate(savedInstanceState);
        
        Bundle args = getArguments();
        if (args != null) {
            mIdx = args.getInt("index", 0);
        }
        
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(this.getClass().getSimpleName(), "onCreateView()");
        return inflater.inflate(R.layout.layout_contents, null);
        
    }
    
    @Override
    public void onInflate(Activity activity, AttributeSet attrs,
            Bundle savedInstanceState) {
        Log.d(this.getClass().getSimpleName(), "onInflate()");
        super.onInflate(activity, attrs, savedInstanceState);
    }
    
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        Log.d(this.getClass().getSimpleName(), "onViewCreated()");
        super.onViewCreated(view, savedInstanceState);
    }
    
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        Log.d(this.getClass().getSimpleName(), "onActivityCreated()");
        super.onActivityCreated(savedInstanceState);
    }
 
    @Override
    public void onStart() {
        Log.d(this.getClass().getSimpleName(), "onStart()");
        super.onStart();
    }
 
    @Override
    public void onResume() {
        Log.d(this.getClass().getSimpleName(), "onResume()");
        super.onResume();
    }
    
    @Override
    public void onPause() {
        Log.d(this.getClass().getSimpleName(), "onPause()");
        super.onPause();
    }
    
    
    

    @Override
    public void onStop() {
        Log.d(this.getClass().getSimpleName(), "onStop()");
        super.onStop();
    }
    
    @Override
    public void onDestroyView() {
        Log.d(this.getClass().getSimpleName(), "onDestroyView()");
        super.onDestroyView();
    }
    
    @Override
    public void onDestroy() {
        Log.d(this.getClass().getSimpleName(), "onDestroy()");
        super.onDestroy();
    }
 
    @Override
    public void onDetach() {
        Log.d(this.getClass().getSimpleName(), "onDetach()");
        super.onDetach();
    }
 
    @Override
    public void onSaveInstanceState(Bundle outState) {
        Log.d(this.getClass().getSimpleName(), "onSaveInstanceState()");
        super.onSaveInstanceState(outState);
    }
 
    
    
}

Fragment실행시 Log를 찍어 보았다. Lifecycle과 동일하게 작동 되는 것을 확인 할 수 있다.

Fragment종료시 Log를 찍어 보았다. Lifecycle과 동일하게 작동 되는 것을 확인 할 수 있다.

Activity에 비해 많은 Callbacks메소드로 인해 복잡한건 사실이다. 하지만 자세히 하나씩 보면 Activity와 별반 다르지 않다는 것을 알 것이다.

아래 그림을 첨부 했으니 Activity와 비교 해보면 좋을것 같다.


+ Recent posts