Anroid Jetpack [ ViewBinding ]

2024. 1. 2. 15:42·Android

[ 안드로이드 공식 문서 ]

 

뷰 결합  |  Android 개발자  |  Android Developers

뷰 결합 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. 뷰 결합 기능을 사용하면 뷰와 상호작용하는 코드를 쉽게 작성할 수 있습니다. 모듈에서 사용 설정

developer.android.com

 

3년전 안드로이드를 처음 공부할 때 만 해도 findViewByID를 사용했던 기억이 납니다. 지금은 이를 대체하기 위한 아주 좋은 도구가 하나 생겼는데 그것이 바로 viewBinding 기법입니다. 

 

📌 ViewBinding 이란 ?

  • xml과 연결되는 바인딩 클래스가 자동으로 생성되어 이 클래스의 멤버로 해당 클래스가 가진 view들을 간편하게 참조할 수 있습니다.
  • 바인딩 클래스는 정해진 명명 규칙에 따라서 만들어집니다.
Activity : activity_main.xml -> ActivityMainBinding
Fragment : fragment_home.xml -> FragmentHomeBinding
item : recycler_item.xml -> RecyclerItemBinding

📌ViewBinding 사용하기

앱 단위의 build.gradle에 아래와 같이 ViewBinding을 사용하겠다고 선언해줍니다.

android {
	...
    buildFeatures {
        viewBinding true
    }
}

 

🔨 Activity에서 사용

class MainActivity : AppCompatActivity(), NavigationBarView.OnItemSelectedListener {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
    }
}

 

🔨 Fragment에서 사용

Fragment에서 ViewBinding을 사용할 때 주의할 점은 onCraeteView( ) 에서 초기화 해줘야 한다는 점입니다. Fragment 생명 주기에서 onCreateView( ) 는 View를 생성할 때 호출합니다. 그러므로 View를 생성함과 동시에 ViewBinding을 완료하면 안전하게 View에 접근할 수 있습니다.

class MyPageFragment : Fragment() {
    private var _binding: FragmentMyPageBinding ?= null
    private val binding get() = _binding!!

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentMyPageBinding.inflate(inflater, container, false)
        return binding.root
    }
}

 

'Android' 카테고리의 다른 글

Android Daum 우편번호 서비스 API With FireBase Hosting  (2) 2024.01.04
Android Base64 Decoding  (0) 2024.01.03
Android LayoutInflater  (1) 2023.12.26
Android Fragment Life Cycle  (0) 2023.12.26
Android Activity Life Cycle  (3) 2023.12.26
'Android' 카테고리의 다른 글
  • Android Daum 우편번호 서비스 API With FireBase Hosting
  • Android Base64 Decoding
  • Android LayoutInflater
  • Android Fragment Life Cycle
빨주노초잠만보
빨주노초잠만보
  • 빨주노초잠만보
    과거의 나를 통해 미래의 나를 성장시키자
    빨주노초잠만보
  • 전체
    오늘
    어제
    • 분류 전체보기 (94)
      • TEKHIT ANDROID SCHOOL (4)
      • Android Architecture (7)
      • Android (40)
      • PROJECT (5)
      • KOTLIN (10)
        • 코루틴의 정석 (3)
      • BACK END (12)
      • CS (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    value class
    flow
    kotlin interface vs abstract
    DI
    callbackflow
    Clean Architecture
    repository
    sealed class vs enum class
    리사이클러뷰 풀
    ThrottleFirst
    코틀린 코루틴의 정석
    DataSource
    Repository Pattern
    Throttle
    android Room
    android clean architecture
    kotlin interface abstract 차이
    Livedata
    kotlin abstract class
    sealed class
    saeled class enum class 차이
    STATEFLOW
    kotlin interface
    MVI
    의존성 주입
    interface vs abstract
    orbit
    kotlin 타입 소거
    kotlin array
    Room
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
빨주노초잠만보
Anroid Jetpack [ ViewBinding ]
상단으로

티스토리툴바