안드로이드/개발 공부

[Android/Kotlin] Kotlin 코드에서 LinearLayout에 동적으로 Custom Layout(<include />) 추가

감자 바보 2022. 4. 4. 16:42
반응형

 안드로이드 개발 중에 코틀린 코드 상에서 LinearLayout에 동적으로 Custom Layout을 추가해야했다. 이 때 사용한 코드를 기술한다.

 

 먼저, AppCompatActivity.getSystemService()를 통해 LayoutInflater를 얻어온다. 

val layoutInflater = this.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

 얻어온 LayoutInflater를 통해 추가(include)할 커스텀 레이아웃을 얻어온다. 

val customLayout = layoutInflater.inflate(R.layout.custom_layout, null)

  커스텀 레이아웃 내부 뷰는 findViewById를 통해 접근할 수 있다.

var textView: TextView = customLayout.findViewById<TextView>(R.id.textView)

 마지막으로 원하는 LinearLayout에 addView()를 사용하여 커스텀 레이아웃을 추가해준다.

binding.linearLayout.addView(customLayout)

 

전체코드

//추가할 커스텀 레이아웃 가져오기
val layoutInflater = this.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val customLayout = layoutInflater.inflate(R.layout.custom_layout, null)
//커스텀 레이아웃 내부 뷰 접근
var textView: TextView = customLayout.findViewById<TextView>(R.id.textView)
//LienarLayout에 커스텀 레이아웃 추가
binding.linearLayout.addView(customLayout)

 

참고


Android Dynamic Include Custom Layout (captainwonjong.github.io)

 

Android Dynamic Include Custom Layout

Android Custom Layout 동적 추가

captainwonjong.github.io