프로그래밍/안드로이드

Android fragment 다루기 - 1.XML에서 추가하기

파머스오 2017. 6. 10. 17:06
반응형

Fragment 개념이 다소 어려울 수도 있지만, 최근 거의 기본적으로 사용되는 사항으로 천천히 살펴볼 예정입니다.

하나의 Activity에 여러개의 fragment를 이용하여 화면 전환 등의 UI를 사용할 수 있습니다.

 

또한 이미 만들어진 fragement를 다른 activity에서도 재사용이 가능합니다.

 

Fragment는 Activity와 유사하게 별도의 생명 주기와 별도의 이벤트에 의해 작동됩니다.

 

우선, Fragment를 추가하는 방법에 대해 다루고, 차후에 생명 주기와 이벤트 등에 대해서 살펴보도록 하겠습니다.

Fragment를 추가하는 방법은 크게 2가지 방법이 있습니다.

 

XML에서 직접 추가하는 방법은 매우 간단하나, 동적 제어가 불가능합니다.

 

동적 제어를 위해서는 Code에서 Fragment를 추가해야하며, 그만큼 복잡해집니다.

 

이번 글에서는 XML에서 추가하는 방법에 대해 간단히 살펴보도록 하겠습니다.

 

 

XML에 추가하는 방법은 위 그림과 같이 레이아웃(XML)과 class를 생성해주고,

 

이를 메인 XML 파일에 <fragment> 태그를 이용하여 간단하게 추가 할 수 있습니다.

 

본 예제에서는 xml 파일과 java파일을 먼저 만들어주고, 후에 태그를 추가 해보도록 하겠습니다.

 

 

일단은 빈 프로젝트를 생성하겠습니다.

 

프로젝트 이름은 'FragmentTest', 타입은 'Empty Activity'로 선택합니다.

 

프로젝트의 Layout resource file에 'fragment_a'를 추가합니다.

출력물에서 fragment 영역을 구분하기 위해 바탕색을 지정하고,

 

TextView하나를 생성하여 Text는 'Fragment A'로 설정합니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFAAAA">
 
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Fragment A"
        android:textSize="15sp"
        android:id="@+id/txtMessage"/>
 
</LinearLayout>
cs

 

 

 

'android.app.Fragment' class를 상속받는 java class를 생성합니다.

 

생성된 class에 onCreateView() 메서드를 오버라이드 해줍니다.

OnCreateView() 내부에 앞서 만든 XML 레이아웃 파일이 표시될 수 있도록 코드를 수정해줍니다.

 

"FragmentA.java"

 

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
package com.fragmenttest;
 
import android.app.Fragment;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
 
/**
 * Created by Jeffry Oh on 2017-06-10.
 */
 
public class FragmentA extends Fragment {
    private TextView mMessage;
 
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
//        View view = inflater.inflate(R.layout.fragment_a, container, false);
 
//        mMessage = (TextView) getActivity().findViewById(R.id.txtMessage);
 
        MyView vw = new MyView(getActivity());
 
//        setContentView(vw);
 
        return vw;
    }
 
 
 
    public void sendMessage(String msg) {
        mMessage.setText(msg);
    }
 
 
    class MyView extends View {
 
        public MyView(Context context) {
            super(context);
        }
 
        @Override
        protected void onDraw(Canvas canvas) {
//            super.onDraw(canvas);
            canvas.drawColor(Color.LTGRAY);
            Paint Pnt = new Paint();
            Pnt.setColor(Color.BLUE);
            canvas.drawCircle(100,100,80,Pnt);
        }
    }
}
 
cs

 

 

마지막으로 activity_main.xml 파일에 fragement 태크를 이용하여 삽입해주면 모든 작업이 완료됩니다.

 

"activity_main.xml"

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="14.5sp"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">
 
 
    <fragment
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:id="@+id/fragmentA"
        android:name="com.fragmenttest.FragmentA"
        tools:layout="@layout/activity_main"       />
 
</LinearLayout>
cs

 

실행해보면 상기와 같이 Fragment A가 삽입된 결과물을 얻을 수 있습니다.

 

다음 글에서는 code에서 추가하는 방법에대해 알아보도록 하겠습니다.

 

 

 

 

 

 

반응형