안드로이드 개발 중에 코틀린 코드 상에서 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
[Android / Kotlin] 안드로이드 14 Notification Ongoing 속성 동작 변경 (0) | 2024.03.14 |
---|---|
[Android / Kotlin] Naver, Github Oauth2 (ACCESSTOKEN 발급) (0) | 2023.04.08 |
[Android/Kotlin] Room 이용 로컬 DB에 사용자 정의 자료형 및 리스트 추가(@Embed, @TypeConverter) (0) | 2022.04.06 |
[Android/Kotlin] 문자열을 이용한 Resource 지정 (0) | 2022.03.14 |
[Android/Kotlin] Fragment에서 context 사용법 (2) | 2022.01.11 |