카테고리 없음

[kotlin] Fragment 적용 하기

훈츠 2020. 1. 30. 13:52
반응형

자바로 프래그먼트를 활용해 보았지만 코틀린으로 작성하려고 하니 약간은 생소해서 기록으로 남겨 놓습니다. 프래그먼트 개념이나 여러가지 설명은 자바의 프래그먼트를 참조 하시고, 이곳에서는 코틀린으로 실행하는 방법만 설명 하도록 하겠습니다. 

 

1. Main Layout 에서 프래그먼트 만들기 (Main액티비티에서 inflation없이 사용시에는 fragment는 사용) 프로그램에서 inflation 원할때는 FrameLayout에 id를 할당 

 

1
2
3
4
5
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
<FrameLayout
    android:id="@+id/fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
cs

 

2. Main 액티비티에서 프래그먼트 매니저 활용해서 inflation 하기. app의 리소스를 생각해서 add보다는 replace 사용

 

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
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
 
//supportFragmentManager 이용
supportFragmentManager.beginTransaction()
            .replace(R.id.fragment,MainFragment()).commit()
 
 
 //개별 프래그먼트로 부터 값 받아서,화면 이동 할시 이용. 
   //프래그먼트
    fun changeFragment(frag : Int){
        val ft = supportFragmentManager.beginTransaction()
        when (frag) {
            MAIN_FRAG -> {
                ft.replace(R.id.fragment, MainFragment()).addToBackStack(null).commit()
            }
            REGIST_FRAG -> {
                ft.replace(R.id.fragment, ContactRegistFragment()).addToBackStack(null).commit()
            }
            SEND_FRAG -> {
                ft.replace(R.id.fragment, SendSmSFragment()).addToBackStack(null).commit()
            }
            LOG_FRAG -> {
                ft.replace(R.id.fragment, SentLogSmSFragment()).addToBackStack(null).commit()
            }
 
        }
 
    }
cs

 

 

3. 프래그먼트 추가 및 inflation : Flagment(blank) 를 생성후 다음 코드 처럼 inflation 할 layout을 지정한다. 

 

1
2
3
4
5
6
7
8
9
10
11
12
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
class MainFragment : Fragment() {
 
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,savedInstanceState: Bundle?): View? {
    
    //R.layout.fragment_main 인프레이션할 프래그먼트 레이아웃 지정
    val view = inflater.inflate(R.layout.fragment_main, container, false)  
    return view
    
    }
}
 
cs

 

4. 프래그먼트 생명주기 

4. onViewCreated : view가 만들어지고 난후 프로그램 하는곳 

: 다음 프래그먼트의 수명주기를 참고하여, 상황에 맞는 곳에 프로그램 해주면 됩니다. 

 

5. onActivityCreated : activitiy 가 만들어지고 난후 프로그램 하는곳 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
 
//프래그먼트에서 액티비티로 부터 값 가져오기 
(activity as MainActivity).changeFragment(MAIN_FRAG) 
 
//프래그 먼트 내에서 부분 화면 인플레이션 시키기 
val inflater = LayoutInflater.from(context)
        inflater.inflate(R.layout.sub_contact_register_view,contact_register,true)
 
//프래그 먼트 내에서 context 객체를 불러오는 방법
requireContext()
        
 
cs

 

6. 결론 :

 

Activity 에서 supportFragmentManager를 통해 프래그먼트를 FrameLayout에 프래그먼트를 로드 합니다. 프래그먼트는 액티비티 위에서 돌아가며, 액티비티 처럼 생명주기를 가지고 있다. 프래그먼트는 액티비티와 다르게 인플레이션 시키고자 하는 뷰를 직접 지정 해줘야 하므로 3* 에서 설명 한것 처럼 인플레이션 시켜 줘야 한다. 그외 액티비티와 다르게 프래그 먼트에서 해줘하는 내용은 5*을 참조 하기 바랍니다. 추가 적으로 계속 업데이트 하도록 하겠습니다. 

반응형