본문 바로가기
안드로이드 자바

[Java][Android] 프래그먼트를 이용한 화면 전환

by teamnova 2021. 3. 2.

오늘은 프래그먼트를 이용한 화면 전환을 해보도록 하겠습니다. 

 

1. 프래그먼트에서 사용할 레이아웃 만들기

우선 각 프래그먼트에서 사용할 xml 레이아웃을 만들어보도록 하겠습니다.

 

fragment_a.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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:background="#FB0606">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="프래그먼트 A"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.234"
        tools:layout_editor_absoluteX="122dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

fragment_b.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FDC600">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="프래그먼트 B"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.234" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

fragment_c.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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:background="#0659FB">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="프래그먼트 C"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.234" />

</androidx.constraintlayout.widget.ConstraintLayout>

각 프래그먼트의 구분을 위해 최상위 레이아웃인 ConstraintLayout의 BackGroud 속성을 다르게 지정하였습니다.

 

2. Fragment를 상속받는 Fragment_A, Fragment_B, Fragment_C 클래스 생성

Fragment_A.java

public class Fragment_A extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_a, container, false);
    }
}

Fragment_B.java

public class Fragment_B extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_b, container, false);
    }
}

Fragment_C.java

public class Fragment_C extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_c, container, false);
    }
}

 

3. FragmentActivity 구현

위에서 정의한 프래그먼트들을 보여줄 액티비티를 구현합니다.

우선 FragmentActivity의 xml을 정의해보도록 하겠습니다.

 

activity_fragment.xml

<?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"
    tools:context=".FragmentActivity"
    android:orientation="vertical">

    <FrameLayout
        android:id="@+id/frame_layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="10"
        tools:layout_editor_absoluteX="203dp"
        tools:layout_editor_absoluteY="281dp">
    </FrameLayout>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        app:menu="@menu/navigation_menu"/>

</LinearLayout>

activity_fragment의 구성요소에는 프래그먼트를 전환 시 필요한 FrameLayout과 BottomNavigationView가 있습니다. 

BottomNavigationView에는 간단한 텍스트만으로 이루어진 3개의 버튼이 보이게 됩니다.

BottomNavigationView에 들어갈 xml 리소스는 res 디렉토리 안에 menu 디렉토리를 만들어서 그 안에 위치시켰습니다.

 

navigation_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/fragment_a"
        android:enabled="true"
        android:title="frag A" />

    <item
        android:id="@+id/fragment_b"
        android:enabled="true"
        android:title="frag B" />

    <item
        android:id="@+id/fragment_c"
        android:enabled="true"
        android:title="frag C" />
</menu>

 

 

마지막으로 FragmentActivity의 코드를 구현해보겠습니다.

FragmentActivity.java

public class FragmentActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment);


        // 프래그먼트 객체 선언
        Fragment fragmentA = new Fragment_A();
        Fragment fragmentB = new Fragment_B();
        Fragment fragmentC = new Fragment_C();

        //제일 처음 띄워줄 뷰를 세팅해줍니다. commit();까지 해줘야 합니다.
        getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, fragmentA).commitAllowingStateLoss();

        // 바텀 네비게이션 객체 선언
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);

        // 바텀 네비게이션 클릭 리스너 설정
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                switch(item.getItemId()){
                  case  R.id.fragment_a:
                      // replace(프레그먼트를 띄워줄 frameLayout, 교체할 fragment 객체)
                      getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, fragmentA).commitAllowingStateLoss();
                      return  true;
                  case  R.id.fragment_b:
                      getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, fragmentB).commitAllowingStateLoss();
                      return  true;
                  case  R.id.fragment_c:
                      getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, fragmentC).commitAllowingStateLoss();
                      return  true;
                  default:
                      return false;
                }
            }
        });
    }

}

저는 바텀 네비게이션의 리스너 설정과 프래그먼트 replace 코드를 스틱코드로부터 불러와서 빠르게 구현했습니다.

 

사용된 스틱코드

stickode.com/code.html?fileno=9469 - fragment_replace

stickode.com/code.html?fileno=9468 - bottom_navi_clickListener

 

 


위의 내용과 같이 구현할 경우 다음와 같은 결과가 보이게 됩니다.