1. 환경설정하기
- 모듈 수준의 gradle에 추가
dataBinding{
enabled = true
}
2. 레이아웃 설정하기
- 최상위 루트 코드를 layout으로 설정하기
<?xml version="1.0" encoding="utf-8"?>
<layout>
<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">
<Button
android:id="@+id/testBtn"
android:text="버튼"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
3. 메인 액티비티
class MainActivity : AppCompatActivity() {
private lateinit var binding : ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 1번 - findViewById이용
/*val btn = findViewById<Button>(R.id.testBtn)
btn.setOnClickListener {
Toast.makeText(this, "클릭됨", Toast.LENGTH_LONG).show()
}*/
// 2번 - Databinding이용
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.testBtn.setOnClickListener {
Toast.makeText(this, "클릭됨", Toast.LENGTH_LONG).show()
}
}
}
'Android > 개념' 카테고리의 다른 글
[안드로이드]JSON 파일 저장 및 파싱 이용해서 리사이클러뷰(RecyclerView)에 적용하기 (0) | 2023.04.02 |
---|---|
[안드로이드]Navigation Component (1) | 2023.03.10 |
[안드로이드] BottomNavigationView (0) | 2023.03.09 |
RecyclerView (0) | 2022.10.10 |
ListView (0) | 2022.10.08 |