Gradle Plugin 3.6.0:
android {
viewBinding {
enabled = true
}
}
Android Studio 4.0 이상:
android {
buildFeatures {
viewBinding = true
}
}
Activity:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding //activity_main.xml
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
}
Fragment:
class ApisFragment : Fragment() {
private var _binding: FragmentApiBinding? = null //fragment_api.xml
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentApiBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.clearLogBtn.setOnClickListener {
binding.log.text = ""
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}