1. View 획득 방법
1) findViewById
2) Butterknife
@BindView(R.id.nameResultView)
lateinit var nameResultView: Textview
@BindView(R.id.button)
lateinit var button: Button
override fun onCreate(savedInstanceState: Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
ButterKnife.bind(this)
nameResultView.text = "minha"
}
@OnClick(R.id.button)
fun onButtonClick(view: View?) {
...
}
3) Kotlin Android Extension (deprecated)
plugins {
id 'kotlin-android-extensions'
}
// xml 파일명 지정
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
nameResultView.text = "hello world"
button.setOnClickListener {
...
}
}
}
4) DataBinding
android {
dataBinding {
enabled = true
}
}
data class User(
val name: String,
val address: String
)
<?xml version="1.0" encoding="utf-8" ?>
<layout>
<data>
<variable
name="user"
type="com.example.test_databinding.User" />
</data>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{user.name + '-' + user.address}" />
<Button
android:id="@+id/button" />
</LinearLayout>
</layout>
class MainActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val biding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
val user = User("gildong", "seoul")
binding.user = user
binding.button.setOnClickListener { }
}
}
1. View 획득 방법 비교
2. ViewBinding
1) build.gradle 선언
android {
viewBinding {
enabled = true
}
}
1-1) Binding 클래스가 필요 없는 경우
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
......
tools:viewBindingIgnore="true">
2) Activity 클래스에서 사용
val binding = ActivityMainBinding.inflate(layoutInflater)
// 액티비티 화면 출력
setContentView(binding.root)
// 뷰 객체 이용
binding.visibleBtn.setOnClickListener {
binding.targetView.visibility = View.VISIBLE
}
binding.invisibleBtn.setOnClickListener {
binding.targetView.visibility = View.INVISIBLE
}