Android
Android Studio_ 8. Fragment (프래그먼트)
아이른
2024. 4. 18. 16:15
1. Fragment (프래그먼트)
- 액티비티 위에서 동작하는 모듈화된 사용자 인터페이스
- 액티비티와 분리되어 독립적으로 동작할 수 없음
![]() |
![]() |
하의 엑티비티 화면 안에서 특정 영역만 화면 교체 | |
![]() |
![]() |
엑티비티 화면전환 |
2. Fragment 사용 이유
- Activity로 화면을 계속 넘기는 것보다는 Fragment로 일부만 바꾸는 것이 자원 이용량이 적어 속도가 빠르기 때문 (재사용 가능한 UI)
- Acrtivity를 적게 만듦
- Acrtivity의 복잡도를 줄임
- Acrtivity를 여러개 만들지 않아도 Acrtivity 안에서 Fragment 공간에 View를 집어넣으면 여러 화면을 만들 수 있음
3. Fragment 생명주기
- onAttach()
- Fragment가 Activity에 연결될 때 호출
- Fragment가 완벽하게 생성된 상태는 아님
- onCreate()
- Fragment 생성될 때 호출
- Activity와 같이 초기화가 필요한 리소스들을 초기화
- Activity의 onCreate() : View나 UI 관련 작업 수행 가능 ↔ Fragment의 onCreate() : UI초기화 x
- onCreateView()
- Fragment의 Layout을 객체화(inflate) 하는 곳
- View를 생성하고, Layout을 설정
- View를 반환 (UI를 제공하지 않으면 Null 반환)
- UI를 그릴 때 호출되는 콜백
onAcitivityCreated 지원 중단- onViewCreated()
- Activity와 Fragment의 View가 모두 생성된 상태이므로, View와 관련된 초기화를 수행
- onViewStateRestored()
- 저장해둔 모든 state 값이 Fragment의 View 계층구조에 복원됐을 때 호출
- onStart()
- Fragment가 사용자에게 보여질 준비가 되어있을 때 호출
- onResume()
- Fragment가 화면에 보여지는 단계
- 사용자와 상호작용할 수 있는 상태가 되었을 때 호출
- onPause()
- Fragment가 일시정지될 때 호출
- onStop()
- Fragment가 더 이상 사용자에게 보이지 않을 때 호출
- onDestroyView()
- Fragment 의 뷰와 관련된 리소스를 정리할 때 호출
- onDestroy()
- 프래그먼트가 파괴될 때 호출
- onDetach()
- 프래그먼트가 엑티비티로부터 분리될 때 호출
4. FragmentManager
- Fragment의 추가, 제거 교체 등의 작업은 FragmentManager에 의해 관리
- supportFragmentManager : 사용자 상호작용에 응답해 Fragment를 추가하거나 삭제하는 등 작업을 할 수 있게 해주는 매니저
- MainActivity → supportFragmentManager로 접근
- MainActivity 안의 ChildFragment
- MainActivity = parentFragmentManager
- ChildFragment of ChildFragment = childFragmentManager
- ChildFragment 안의 ChildFragment → parentFragmentManager로 접근
- Fragment는 Fragment Backstack 존재
- addToBackStack : 뒤로가기 버튼 클릭시 다음 액션 (이전 Fragment로 가거나 앱이 종료되거나)
- Fragment Transaction
- commit : main UI 쓰레드에서 수행 가능한 시점이 되면 수행
- commitNow (ViewPager2에서 사용됨) : 즉시 수행, 단 addToBack 불가능
- replace, add, remove, show, hide 등
- replace
- fragment를 fragmentContainer에서 교체
- 매번 view를 생성하고 destroyView 호출
- add
- 단순히 fragment를 추가
- view를 create하고 destroyView를 하지 않음
- replace
- setReorderingAllowed : 애니메이션과 전환이 올바르게 작동하도록 트랜잭션과 관련된 프래그먼트의 상태 변경을 최적화
5. Fragment 사용
- New > Fragment > Fragment(Blank)
- Fragment & frahment.xml 자동 생성
- buildgradle.kts 설정
dependencies {
...
implementation("androidx.fragment:fragment-ktx:1.6.2")
...
}
5. Fragment 예제
활용 1. 버튼 2개를 생성하여 버튼을 눌렀을 때 화면 전환
- android:textAllCaps = "true" : 알파벳 대문자 만들기
더보기
<?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="match_parent"
android:layout_height="0dp"
android:layout_marginStart="15dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="15dp"
android:layout_marginBottom="15dp"
app:layout_constraintBottom_toTopOf="@id/btn_flag1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn_flag1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginBottom="15dp"
android:text="flag1"
android:textAllCaps="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@id/btn_flag2"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="@+id/btn_flag2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginBottom="15dp"
android:text="flag2"
android:textAllCaps="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@id/btn_flag1" />
</androidx.constraintlayout.widget.ConstraintLayout>
![]() |
![]() |
fragment_first.xml | fragment_second.xml |
더보기
//fragment_fitst.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#ED9EF6"
tools:context=".FirstFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="프래그먼트 1"
android:textSize="40sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="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:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#F850CE"
tools:context=".FirstFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="프래그먼트 2"
android:textSize="40sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
class MainActivity : AppCompatActivity() {
private lateinit var binding : ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.apply {
btnFlag1.setOnClickListener {
setFragment(FirstFragment())
}
btnFlag2.setOnClickListener {
setFragment(SecondFragment())
}
}
setFragment(FirstFragment())
//앱을 실행시켰을 때 먼저 보여줄 프래그먼트 설정
}
private fun setFragment(frag:Fragment){
supportFragmentManager.commit {
replace(R.id.frameLayout, frag)
setReorderingAllowed(true)
addToBackStack("")
}
}
}