320x100
지금까지의 글은 모두 findViewById 를 사용해
Button 이나 TextView 들의 객체를 가져왔지만
매번 findViewById를 사용하면
코드가 길어질 뿐더러
필요한 이벤트가 있을 때마다
객체들을 모두 전역변수로 만들어
findViewById를 사용해야한다
view Binding을 사용하면
이러한 점들을 고치고
전역변수를 1개를 두어
findViewById를 사용하지 않고
객체를 사용하는 것이 가능하다
코드 1 : MainActivity.kt
class MainActivity : AppCompatActivity() {
/**
* @Android 공식 사이트 : https://developer.android.com/topic/libraries/view-binding?hl=ko
*
* 사용하는 layout xml 이름을 '카멜표기법' 으로 변환하고
* 뒤에 'Binding' 을 붙이면 된다
* 예) layout 이름 : activity_main -> ActivityMainBinding
*/
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// binding 초기화
binding = ActivityMainBinding.inflate(layoutInflater)
// contentView 적용
setContentView(binding.root)
// findViewById 없이 바로 사용
binding.bTest.setOnClickListener { buttonTest() }
}
private fun buttonTest() {
// findViewById 없이 바로 사용
binding.tvMsg.text = "button click !!"
}
}
코드 2 : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/b_test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Button"
app:layout_constraintEnd_toEndOf="@+id/tv_msg"
app:layout_constraintStart_toStartOf="@+id/tv_msg"
app:layout_constraintTop_toBottomOf="@+id/tv_msg" />
</androidx.constraintlayout.widget.ConstraintLayout>
코드 3 : build.gradle (app)
plugins {
...(생략)
}
android {
...(생략)
// 해당 부분 추가 후 Sync
viewBinding {
enabled = true
}
}
dependencies {
...(생략)
}
320x100
'Android > Kotlin' 카테고리의 다른 글
[Android][Kotlin] strings.xml 파일 동적으로 데이터 처리 및 가져오기 (0) | 2022.10.31 |
---|---|
[Android][Kotlin] 캘린더(Calendar)로 오늘 날짜(today), 마지막 일(last day) 가져오기 (0) | 2022.10.24 |
[Android][Kotlin] 단말기(device) 가로 세로 실제 해상도 가져오기 (0) | 2022.10.21 |
[Android][Kotlin] Thread 에러 처리 및 UI 변경 활용 예제 (0) | 2022.10.20 |
[Android][Kotlin] 알람매니저(AlarmManager)를 이용한 알림(Notification) 호출하기 (0) | 2022.10.14 |