(kotlin) Fragment

박용석·2023년 8월 24일
1

프래그먼트(Fragment)란?

  • 액티비티 위에서 동작하는 모듈화된 사용자 인터페이스
    (액티비티와 분리되어 독립적으로 동작할 수 없음)
  • 여러 개의 프래그먼트를 하나의 액티비티에 조합하여 창이 여러개인 UI를 구축할 수 있으며, 하나의 프래그먼트를 여러 액티비티에서 재 사용할 수 있음

프래그먼트의 사용이유

  1. Activity로 화면을 계속 넘기는 것보다는 Fragment로 일부만 바꾸는 것이 자원 이용량이 적어 속도가 빠르기 때문이다.
  2. Fragement를 사용하면 Activity를 적게 만들 수 있다.
  3. Activity의 복잡도를 줄일 수 있다.
  4. 재사용할 수 있는 레이아웃을 분리해서 관리가 가능하다
  5. 최소 1개의 Activity안에서 Fragment 공간에 View만 집어넣으면 여러 Activity를
    만들지 않아도 여러 화면을 보여줄 수 있다.

kotlin 소스 파일 생성

  • 프래그먼트를 생성하려면 fragment의 서브클래스를 생성
  • 프래그먼트에 대해 레이아웃을 제공하려면 반드시 onCreateView() 콜백 메서드를 구현
class FirstFragment : Fragment() {  
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false)
    }

inflate()함수를 통해서 fragment_first.xml 파일로부터 레이아웃을 로드

kotlin 코드에서 동적으로 프래그먼트 추가하기

supportFragmentManager.commit {
            replace(R.id.frameLayout, frag)
            setReorderingAllowed(true)
            addToBackStack("")
        }

supportFragmentManager
사용자 상호작용에 응답해 fragment를 추가하거나 삭제하는등 작업을 할 수 있게 해주는 매니저

replace
어느 프레임 레이아웃에 띄울것인지, 어떤프래그먼트인지

setReoderingAllowed
애니메이션과 전환이 올바르게 작동하도록 트랜잭션과 관련된 프래그먼트의 상태 변경을 최적화

addToBackStack
뒤로가기 버튼 클릭시 다음 액션 (이전 fragment로 가거나 앱 종료되거나)

  • 프래그먼트 실습 예제
    res > New > Fragment > Fragment(Blank)를 이용하여 생성

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>

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>

activity_main.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"
    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>

MainActivity.kt

class MainActivity : AppCompatActivity() {

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

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

        binding.apply {
            fragment1Btn.setOnClickListener{
                setFragment(FirstFragment())
            }
            fragment2Btn.setOnClickListener {
                setFragment(SecondFragment())
            }
        }
        setFragment(FirstFragment())
    }

    private fun setFragment(frag : Fragment) {
        supportFragmentManager.commit {
            replace(R.id.frameLayout, frag)
            setReorderingAllowed(true)
            addToBackStack("")
        }
    }
}
  • 주의할점
    supportFragmentManager.commit을 사용하기 위해서는 build.gradle에 dependecies에 fragment 추가를 해줘야 사용 가능함
    implementation("androidx.fragment:fragment-ktx:1.6.1")
profile
슬기로운 개발 활동

4개의 댓글

comment-user-thumbnail
2023년 8월 24일

엇 쓰다 만 것 같은 이 느낌은 뭐죠...?!?!?!ㅋㅋㅋㅋㅋㅋㅋㅋㅋ

1개의 답글
comment-user-thumbnail
2023년 8월 24일

어랏... 눈이 아파요 회원님 ^^... 담엔 사진도 넣어주세요...

1개의 답글