MainActivity

...더보기
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
package com.example.boostcoursepractice;
 
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
 
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;
 
public class MainActivity extends AppCompatActivity {
 
    Button button ;
    Button button2 ;
    MainFragment mainFragment;
    SubFragment subFragment;
    //FrameLayout frameLayout ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        mainFragment = new MainFragment();
        subFragment  = new SubFragment();
 
        button = (Button) findViewById(R.id.button);
        button2 = (Button) findViewById(R.id.button2);
        //        //frameLayout = (FrameLayout) findViewById(R.id.frame_layout);
 
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //getSupportFragmentManager().beginTransaction().add(R.id.frame_layout, mainFragment).commit();
                getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, mainFragment).commit();
            }
        });
 
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, subFragment).commit();
            }
        });
    }
 
    public void chageFragement(int n)
    {
        if(n == 0)
        {
            getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, mainFragment).commit();
        }
        else if(n==1)
        {
            getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, subFragment).commit();
        }
    }
}
 
 
cs

 

MainFragment

...더보기
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
package com.example.boostcoursepractice;
 
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
 
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
 
public class MainFragment extends Fragment {
 
    MainActivity activity ;
 
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
 
        activity = (MainActivity) getActivity();
    }
 
    @Override
    public void onDetach() {
        super.onDetach();
 
        activity = null;
    }
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
 
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_main, container, false) ;
        Button btn = (Button) rootView.findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                activity.chageFragement(1);
            }
        });
        return rootView;
    }
}
 
cs

 

SubFragment

...더보기
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
package com.example.boostcoursepractice;
 
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
 
import androidx.fragment.app.Fragment;
 
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
 
public class SubFragment extends Fragment {
 
    MainActivity activity ;
 
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Toast.makeText(context, "attach 실행됨", Toast.LENGTH_LONG).show();
 
        activity = (MainActivity) getActivity();
    }
 
    @Override
    public void onDetach() {
        super.onDetach();
        Toast.makeText(getActivity(), "onDetach 실행됨", Toast.LENGTH_LONG).show();
 
        activity = null;
    }
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        Toast.makeText(getActivity(), "onCreateView 실행됨", Toast.LENGTH_LONG).show();
 
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_sub, container, false) ;
        Button btn = (Button) rootView.findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                activity.chageFragement(0);
            }
        });
        return rootView;
    }
}
 
cs

 

activity_main.xml

...더보기
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
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
 
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="시작" />
 
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@id/button"
        android:text="메뉴" />
 
    <FrameLayout
        android:id="@+id/frame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/button">
        <!--
        <fragment
            android:id="@+id/fragment"
            android:name="com.example.boostcoursepractice.MainFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
        -->
    </FrameLayout>
 
 
 
 
</RelativeLayout>
cs

 

fragment_main.xml

...더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_orange_light"
    android:orientation="vertical">
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="프래그먼트 1"
        android:textSize="40dp"
        />
 
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="서브화면으로" />
 
 
</LinearLayout>
cs

 

fragment_sub.xml

...더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/design_default_color_primary"
    android:orientation="vertical">
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="프래그먼트 2"
        android:textSize="40dp" />
 
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="메인화면으로" />
 
 
</LinearLayout>
cs

 

우선 프래그먼트를 이해하기 위해서는 아래의 그림을 이해해야 한다.

이처럼 액티비티를 전환하는 것은 시스템의 액티비티 매니저가 하지만 프래그먼트의 전환은 액티비티 안에 프래그먼트 매니저가 관리한다. 따라서 액티비티가 중심이 된다는 것을 잊지 말아야한다.

 

프래그먼트의 객체화는 

 

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

 

이 함수에서 이루어 진다.

 

 

 

 

메인액티비티에 나와 있는 것처럼 우선

 

mainFragment = new MainFragment();

subFragment  = new SubFragment();

 

이렇게 프래그먼트를 만들어주고 

 

getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, mainFragment).commit();

 

이런 함수를 통하여 액티비티 매니저를 이용하여 액티비티에 프래그먼트를 만들어 붙여 줘야 한다. 이 함수가 실행 될 때부터 프래그먼트의 수명주기가 시작이 된다.

 

또한 프래그먼트에서 다른 프래그먼트를 띄워 줄 때 프래그먼트 안에서 바로 띄워 줄 수 없고 해당 프래그먼트를 만들어준 액티비티를 통해 다른 프래그먼트를 띄워야 한다. (앞서 그림에서 설명한 이론 액티비티 중심) 따라서

 

activity = (MainActivity) getActivity();

 

이렇게 프래그먼트를 만들어준 액티비티를 얻고 

 

activity.chageFragement(1);

 

그 액티비티의 함수(액티비티 매니저를 통해 다른 프래그먼트를 띄울수 있게 정의함)를 실행하여 액티비티의 액티비티매니저를 통해 다른 프래그먼트를 띄울 수 있도록 해야 한다.

 

 

 

 

*****************************************************************************************8

마지막 참고로 프래그먼트를 그냥 xml 파일에서

 

 <fragment

            android:id="@+id/fragment"

            android:name="com.example.boostcoursepractice.MainFragment"

            android:layout_width="match_parent"

            android:layout_height="match_parent" />

 

이런식으로 코드가 아닌 태그로 추가할 수도 있다.

 

 

**중요1 : 프래그먼트에서 액티비티를 띄울 때 프래그먼트를 생성한 액티비티를 통해서 띄워야 된다. 따라서 프래그먼트에서 getActivity().startActivityResult()를 해야만 한다. 

 

**중요2 : 프래그먼트를 껐다가 다시 키긴보다는 transaction().hide() / transaction().show() 를 많이 이용하자 뭔가 다시 키면 리스트뷰나 뷰페이저가 다시 뜨지를 않는다.

 

 

 

 

결과화면 1

 

결과화면2

 

+ Recent posts