«   2024/09   »
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
Archives
Today
Total
관리 메뉴

[위미르 개발팀] Android, iOS , Web 제작

[안드로이드 레이아웃]Fragment 사용하기 본문

개발자료/Android

[안드로이드 레이아웃]Fragment 사용하기

위미르개발팀 2017. 9. 22. 11:09

안드로이드에서는 화면을 바꿀때 두가지 방법이 제공됩니다.


화면 하나를 구성하고있는 액티비티를 새로 띄우는 방법과, 액티비티의 일부분을 교체하는 프래그먼트 방식이 있습니다.


두가지방식의 차이는 당연히 존재합니다.


먼저 시각적으로는 액티비티를 새로 띄우는경우 화면전체가 깜빡인다던지 하는것을 볼 수 있고, 프래그먼트는 그부분만 변경됩니다.


둘다 장단점은 존재 합니다만, 모바일에서 많이 사용하는 방식인 여러탭으로 화면을 전환하거나, 사이드메뉴에서 화면을 전환한다던지 하는 기본틀은 유지한채 여러화면이 구성되는 방식에서는 프래그먼트가 보기에도 좋고 구현하기도 편합니다.

액티비티는 추가할때마다 메니페스트에 추가 해주어야 하지만 프래그먼트는 그런것이 없습니다.

하지만 액티비티로 할수있는것이 있고 프래그먼트로 할수있는것이 있기때문에 적절한곳에 사용하셔야 합니다.


사용법입니다.


우선 액티비티에 프래그먼트로 채울 영역을 설정합니다.


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
<?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"
    tools:context="com.wimir.wimir.MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="전환1"
            android:id="@+id/bt1"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="전환2"
            android:id="@+id/bt2"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="전환3"
            android:id="@+id/bt3"/>
    </LinearLayout>
 
    <FrameLayout
        android:id="@+id/main_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
cs



하단의 프레임레아웃이 프래그먼트로 사용할 영역입니다.



영역은 이렇게 잡혀 있습니다.


다음은 프래그먼트를 구성할 xml을 작성합니다.


1
2
3
4
5
6
7
8
9
10
11
<?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="#AAD">
    <TextView
        android:text="프래그먼트 1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
 
</LinearLayout>
cs


저는 프래그먼트 3개를 사용할것이기때문에 버튼 3개를 배치 했고, 3가지 모두 위의 코드에서 배경색상과 텍스트만 다릅니다.


다음은 프래그먼트를 표현할 클래스입니다. 

Fragment를 상속받아서 사용합니다.


1
2
3
4
5
6
7
8
9
10
11
public class Frag1 extends Fragment {
    View view;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.frag1, container, false);
 
        return view;
    }
}
 
cs


다음은 메인액티비티 입니다.


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
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    Button bt1,bt2,bt3;
    FragmentManager fm;
    FragmentTransaction tran;
    Frag1 frag1;
    Frag2 frag2;
    Frag3 frag3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt1 = (Button) findViewById(R.id.bt1);
        bt2 = (Button) findViewById(R.id.bt2);
        bt3 = (Button) findViewById(R.id.bt3);
        bt1.setOnClickListener(this);
        bt2.setOnClickListener(this);
        bt3.setOnClickListener(this);
        frag1 = new Frag1(); //프래그먼트 객채셍성
        frag2 = new Frag2(); //프래그먼트 객채셍성
        frag3 = new Frag3(); //프래그먼트 객채셍성
        setFrag(0); //프래그먼트 교체
    }
    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.bt1:
                setFrag(0);
                break;
            case R.id.bt2:
                setFrag(1);
                break;
            case R.id.bt3:
                setFrag(2);
                break;
        }
    }
    public void setFrag(int n){    //프래그먼트를 교체하는 작업을 하는 메소드를 만들었습니다
        fm = getFragmentManager();
        tran = fm.beginTransaction();
        switch (n){
            case 0:
                tran.replace(R.id.main_frame, frag1);  //replace의 매개변수는 (프래그먼트를 담을 영역 id, 프래그먼트 객체) 입니다.
                tran.commit();
                break;
            case 1:
                tran.replace(R.id.main_frame, frag2);  //replace의 매개변수는 (프래그먼트를 담을 영역 id, 프래그먼트 객체) 입니다.
                tran.commit();
                break;
            case 2:
                tran.replace(R.id.main_frame, frag3);  //replace의 매개변수는 (프래그먼트를 담을 영역 id, 프래그먼트 객체) 입니다.
                tran.commit();
                break;
        }
    }
}
cs


각각의 버튼을 누르면 순서에 맞는 프래그먼트가 들어가도록 하였습니다.


setFrag에 들어있는 tran은 한번만 초기화하고 사용하면 에러가 납니다. 바꿀때마다 초기화 해주어야 합니다.


다음은 실행 화면 입니다.





각각의 버튼을 누를때마다 화면이 바뀌는 모습입니다.


안드로이드 프로그래밍을  조금 하시다 보면 이럴땐 프래그먼트를 써야겠다, 액티비티를 써야겠다, 감이 잡히실것입니다.





희 위미르에서는 모바일 어플리케이션(Android/iOS), Web 개발을 해드리고 있습니다.


문의 전화 : 070-4177-3962

Comments