[ kotlin ] Fragment 통신 - Bundle + 인터페이스

·2023년 12월 8일
0

Mobile-Software

목록 보기
5/15
post-thumbnail

Fragment 통신

Bundle + 인터페이스



  • companion_object 블록은 클래스의 정적 멤버 선언하는데 사용. `newInstance1 라는 정적 팩토리 메서드 정의
const val ARG_PARAM = "fragment_B"


companion object {
        @JvmStatic
        fun newInstance(params: String) =
            /* val bundle = Bundle()
             bundle.putString(ARG_PARAM, params)
             arguments = bundle*/
            FragmentB().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM, params)
                }
            }
    }

아래 코드로 바꿔 작성할 수 있다.

val bundle = Bundle()
bundle.putString(ARG_PARAM, params)
arguments = bundle



  • word 라는 이름으로 가변 변수를 선언
    null 값을 가질 수 있도록 String? 형식으로 선언
  • argument : Fragement 에 전달된 인수를 나타내는 속성
    안전 호출 연산자 ?. 로, argument 가 null 이 아닌 경우에만 코드 블록 실행
  • let 함수 는 람다 함수를 호출하는데 사용되고, 이 람다 함수에서의 itargument를 가리킨다.
  • it.getString(ARG_PARAM) 은 Fragment 에 전달된 인수 중에서 ARG_PARAM 키에 해당하는 문자열을 가져오고, 이 값을 변수 word 에 할당

=> Fragment 의 arguments 로 전달된 문자열 값을 가져와 이를 binding.textView.text 에 표시하는 코드

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val binding = FragmentBBinding.inflate(inflater, container, false)
        var word: String? = null
        arguments?.let {
            word = it.getString(ARG_PARAM)
            binding.textView.text = word
        }









0개의 댓글