Android 11.0 API Level 30 기준
build.gradle (Module)
[code]
android {
buildFeatures {
viewBinding = true
}
// 4.0 이하일 경우
viewBinding {
enabled = true
}
}
[/code]
※ 예를들어 레이아웃에서 user_item.xml 이란 파일을 만들면 자동으로 UserItemBinding 클래스가 만들어진다.
Activity 에서 사용하기
[code]
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.button1.setOnClickListener(object: View.OnClickListener {
override fun onClick(v: View?) {
// todo
}
})
}
….
}
[/code]
Fragment 에서 사용하기
[code]
class MainFragment : Fragment() {
private lateinit var binding: FragmentMainBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentMainBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.btnNext.setOnClickListener {
// TODO
}
}
}
[/code]
RecyclerView 에서의 viewBinding
[code]
class UserListAdapter(private val userList: List<User>): RecyclerView.Adaper<UserListAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserListAdapter.ViewHolder {
val binding = UserItemBinding.inflate(
LayoutInflater.from(parent.content),
parent,
false)
return viewHolder(binding)
}
override fun onBindingViewHolder(holder: UserListAdapter.ViewHolder, position: Int) {
val user = userList[position]
holder.itemBinding.tvUserItem1.text = user.username
holder.itemBinding.tvUserItem2.text = user.age.toString()
}
override fun getItemCount() = userList.size
class ViewHolder(val itemBinding: UserItemBinding): RecyclerView.ViewHolder(itemBinding.root)
}
[/code]