독립된 실행단위가 아닌 화면만 필요한 경우 사용
Fragment에서 동작하는 기능 : onCreateView에 작성
class PostListFragment : Fragment() {
lateinit var mainActivity: MainActivity
lateinit var fragmentPostListBinding: FragmentPostListBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
mainActivity = activity as MainActivity
fragmentPostListBinding = FragmentPostListBinding.inflate(inflater)
return fragmentPostListBinding.root
}
}
companion object {
// Activity가 관리할 프래그먼트 이름
val MAIN_FRAGMENT = "MainFragment"
val ADD_FRAGMENT = "AddFragment"
val RESULT_FRAGMENT = "ResultFragment"
}
replaceFragment(MAIN_FRAGMENT, false, false)
fun replaceFragment(name: String, addToBackStack: Boolean, animate: Boolean) {
// Fragment 교체 상태로 설정
val fragmentTransaction = supportFragmentManager.beginTransaction()
// 새로운 Fragment를 담을 변수
var newFragment = when (name) {
MAIN_FRAGMENT -> {
MainFragment()
}
ADD_FRAGMENT -> {
AddFragment()
}
RESULT_FRAGMENT -> {
ResultFragment()
}
else -> {
Fragment()
}
}
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)
}
// 교체 명령 동작
fragmentTransaction.commit()
}
}
fun removeFragment(name: String) {
supportFragmentManager.popBackStack(name, 0)
}
method 사용 방법
mainActivity.removeFragment(JOIN_FRAGMENT) mainActivity.replaceFragment(ADD_USER_INFO_FRAGMENT,true,null)