일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- list adapter
- 안드로이드
- HotStream
- DI
- ColdStream
- koltin
- 의존성주입
- compose
- 화면전환
- 다른버전 다운로드
- fragment
- Kotlin
- 안드로이드 스튜디오 구버전 다운받기
- 뷰모델팩토리
- 어댑터 효율적으로 사용하기
- Android
- Clean Architecture
- 클린아키텍처
- error
- 키보드 숨기기
- android aac
- hilt
- notifyDataSetChanged 대신 사용하기
- 앱개발
- 코틀린
- SQLite
- 계층 분리
- 안드로이드 DB
- notifyDataSetChanged 비효율
- DiffUtilCallback
Archives
- Today
- Total
DoReMi
[Kotlin] Fragment - 프래그먼트(분기) 본문
▶ 프래그먼트란?
액티비티 내에 배치되어 사용자 인터페이스를 구성하는 안드로이드 구성요소 중 하나입니다.
다른 UI를 독립적으로 보여주고 싶을 때 프래그먼트를 사용한다.
프래그먼트는 액티비티 내에만 존재할 수 있다.
프래그먼트는 상태와 백스택을 가질 수 있다.
프래그먼트는 액티비티가 파괴되면 프래그먼트도 모두 파괴된다.
액티비티가 중지되면 프래그먼트도 중지된다.
▶ 예시
MainActivity.kt - onCreate
// 지정한 Fragment를 보여주는 메서드
fun replaceFragment(name:FragmentName, addToBackStack:Boolean, animate:Boolean){
// Fragment 교체 상태로 설정한다.
val fragmentTransaction = supportFragmentManager.beginTransaction()
// 새로운 Fragment를 담을 변수
// 이름으로 분기한다.
var newFramgnet = when(name){
FragmentName.FRAGMENT_MAIN -> {
MainFragment()
}
FragmentName.FRAGMENT_INPUT -> {
InputFragment()
}
FragmentName.FRAGMENT_RESULT ->{
ResultFragment()
}
}
if(newFragment != null) {
// Fragment를 교채한다.
fragmentTransaction.replace(R.id.mainContainer, newFragment)
if (animate == true) {
// 애니메이션을 설정한다.
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
}
if (addToBackStack == true) {
// Fragment를 Backstack에 넣어 이전으로 돌아가는 기능이 동작할 수 있도록 한다.
fragmentTransaction.addToBackStack(name.str)
}
// 교체 명령이 동작하도록 한다.
fragmentTransaction.commit()
}
}
백스택 제거 메소드
// Fragment를 BackStack에서 제거한다.
fun removeFragment(name:FragmentName){
supportFragmentManager.popBackStack(name.str, FragmentManager.POP_BACK_STACK_INCLUSIVE)
}
MainActivity Class 밖
enum class FragmentName(var str:String){
FRAGMENT_MAIN("MainFragment"),
FRAGMENT_INPUT("InputFragment"),
FRAGMENT_RESULT("ResultFragment"),
}
프래그먼트 간에 데이터를 전달해야하는 경우 replaceFragment 함수에 매개변수로 Bundle을 만들어 Bundle 객체를 전달한다.
val newBundle = Bundle()
newBundle.putString("Key", 전달할 데이터)
데이터를 받는 화면에서는 다음과 같이 가져올 수 있다.
val key = arguments?.getString("Key")
'Android > 개념' 카테고리의 다른 글
[Kotlin] Firebase Console (0) | 2023.07.31 |
---|---|
[Kotln] 네이버 지도 API 사용법 (0) | 2023.07.26 |
[Kotlin] Google Map(LBS - 위치기반서비스) (0) | 2023.07.20 |
[Kotlin] Splash Screen(스플래쉬 스크린) (0) | 2023.07.19 |
[Kotlin] Android MVVM 패턴 (0) | 2023.07.14 |