본문 바로가기
Android Studio

[Android 앱개발 숙련] 프래그먼트 예제 실습 (# 추가하기)

by 젼젼39 2024. 4. 11.

1. 프래그먼트 정의하기

1) 새 프로젝트 만들기 (ex. FragmentExample)

2) 안드로이드스튜디오에서 File > New > Fragement > Fragment(Blank) 를 이용해 쉽게 생성하기
        // MainActivity 우클릭 > New > Fragment > Fragment(Blank) 도 동일함

3) ConfigureComponent 대화 창에서 아래와 같이 설정 후, [Finish] 버튼 클릭

    - FragmentName 값을 FirstFragment로 설정

    - FragmentLayoutName 값을 fragment_first로 설정

    - SourceLanguage : Kotlin

4) [확인] 프로젝트에서 다음의 변경사항을 확인하기 

    - FirstFragment 클래스가 생성됨

    - fragment_first.xml 파일이 생성됨

5) 자동으로 생성된 fragment_first.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:background="#F19B9B"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="프래그먼트 1"
        android:textAllCaps="false"
        android:textSize="40sp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

6) 자동으로 생성된 fragment_second.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:background="#C785D3"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="프래그먼트 2"
        android:textAllCaps="false"
        android:textSize="40sp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

2. 프래그먼트를 액티비티의 레이아웃 파일에 정적 추가하기

1) activity_main.xml 파일을 열고, fragment를 표시할 FrameLayout 과 버튼 2개 추가

<?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"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="10dp"
        app:layout_constraintBottom_toTopOf="@+id/fragment1_btn"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
    </FrameLayout>

    <Button
        android:id="@+id/fragment1_btn"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Frag1"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/fragment2_btn"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/frameLayout" />

    <Button
        android:id="@+id/fragment2_btn"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Frag2"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/fragment1_btn"
        app:layout_constraintTop_toBottomOf="@+id/frameLayout" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

2) MainActivity.kt 에 Fragment 추가하기

class MainActivity : AppCompatActivity() {

    private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        //코드 가독성 높이기 위해 apply 사용
        binding.apply {
            fragment1Btn.setOnClickListener{
                //setFragment에 FirstFragment()를 파라미터로 전달
                setFragment(FirstFragment())
            }
            fragment2Btn.setOnClickListener {
                setFragment(SecondFragment())
            }
        }
        //프로그램이 시작될 때 FirstFragment를 뿌리라고 코드 작성함
        setFragment(FirstFragment())
    }

    private fun setFragment(frag : Fragment) {
        //동적
        //setFragment가 불리면 전달받은 프래그먼트로 전환하는 것
        supportFragmentManager.commit {
            //frameLayout에 전달받은 프래그먼트를 뿌릴 것임
            replace(R.id.frameLayout, frag)
            setReorderingAllowed(true)
            addToBackStack("")
        }
    }
}

    //setFragment(FirstFragment()) 를 두 번 작성한 이유
       - 첫 번째 호출은 앱이 시작될 때 초기 화면을 설정하기 위한 것이고,
        - 두 번째 호출은 버튼 클릭 등의 이벤트에 의해 프래그먼트를 전환하는 데 사용됨

 

    // build.gradle (Module : app) 에 주석 아래 코드 추가하고 싱크하기

dependencies {

    implementation(libs.androidx.core.ktx)
    implementation(libs.androidx.appcompat)
    implementation(libs.material)
    implementation(libs.androidx.activity)
    implementation(libs.androidx.constraintlayout)
    
    //fragment 라이브러리 추가하기
    implementation("androidx.fragment:fragment-ktx:1.6.2")

    testImplementation(libs.junit)
    androidTestImplementation(libs.androidx.junit)
    androidTestImplementation(libs.androidx.espresso.core)
}