Android(Kotlin)

Android Kotlin Viewbinding(Databinding)

----___<<<<< 2020. 12. 14. 12:55

 안드로이드 xml에 접근하여 데이터를 수정, 변경하는 방법에는 여러가지가 있습니다.

 

 우리가 늘 하듯이

 

 1 - findViewbyId 를 이용하는 방법

 2 - Android Kotlin Extension 를 이용하는 방법

 

 대표적으로 2가지가 있지만, 1 - findViewbyId같은 경우에는 코드로 정리할 경우, 코드가 불필요하게 길어지는 경향이 있으며 2- Android Kotlin Extension 같은 경우에는, xml파일이 많아질 수록 헷갈릴 수도 있고, 안드로이드 스튜디오 버전 4.x부터 지원을 중단하였습니다. 

 

 때문에, 우리는 새로운 방법을 알아봐야 하는데, 이번에 소개드릴 방법은 DataBinding을 이용하는 방법입니다.

 

 이 방법은 안드로이드 스튜디오 버전 4.x부터 적용이 되니 참고하시면 좋을 것 같습니다.

 

 우선적으로 build.gradle파일로 가서 아래와 같이 추가해줍니다.

 

buildFeatures {
viewBinding = true
}
view raw text.gradle hosted with ❤ by GitHub

 헷갈리실까봐 전체 파일을 보여드리면 아래와 같은 위치입니다.

 

 자, 그렇다면 여기까지 하고 Activity로 와서 View를 연결해줘야 합니다.

 

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.my.himchanyoon.listviewtest.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
// Main 부분은 Activity의 이름
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// 뷰 바인딩
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// xml에 testId라는 항목에 접근하여 text변경
binding.testId.setText("여기는 텍스트")
}
}
view raw main.kt hosted with ❤ by GitHub
<?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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="30dp"
android:id="@+id/test_id"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
view raw aa.xml hosted with ❤ by GitHub

 이렇게 하면 View에 접근해서 텍스트를 변경해줄 수 있습니다.

 

 

 

'Android(Kotlin)' 카테고리의 다른 글

Android Log찍기, TAG달기  (0) 2020.12.14
Android Kotlin ImageSlider(PagerAdapter)  (0) 2020.12.14
Android Kotlin RecyclerView  (0) 2020.12.14
Android Kotlin Splash  (0) 2020.12.14
Android Kotlin ListView  (1) 2020.12.14