Upgrade to Pro — share decks privately, control downloads, hide ads and more …

How to use ViewBinding in Android Studio 3.6

Su Myat
October 01, 2019

How to use ViewBinding in Android Studio 3.6

In Android Studio 3.6, we can use ViewBind which introduced in Google I/O 2019 “What’s new in Android” talk. I shared about what’s view binding, how do we access the view on android, make some practices with findviewbyId, data binding, and view binding.

Su Myat

October 01, 2019
Tweet

More Decks by Su Myat

Other Decks in Programming

Transcript

  1. Contents 1.WHY THIS TALK Because you can use ViewBindings in

    Android Studio 3.6 Canary11+ 2. ACCESSING VIEWS Let’s look up options what we have and evaluate them in terms of elegance, the compile time safety and the build speed impact. 3. HOW TO USE Go back findViewByID, then Data Binding and View Binding.
  2. ViewBinding/DataBinding can provide a nice way of directly calling views

    by id with just initializing one variable - the binding class.
  3. Let’s look up options we have? Method Elegance Compile Type

    Safety Build Speed findViewById Data Binding
  4. Let’s look up options we have? Method Elegance Compile Type

    Safety Build Speed findViewById Data Binding Butterknife
  5. Let’s look up options we have? Method Elegance Compile Type

    Safety Build Speed findViewById Data Binding Butterknife Kotlin Synthethic
  6. Let’s look up options we have? Method Elegance Compile Type

    Safety Build Speed findViewById Data Binding Butterknife Kotlin Synthethic ???
  7. Let’s look up options we have? Method Elegance Compile Type

    Safety Build Speed findViewById Data Binding Butterknife Kotlin Synthethic View Binding
  8. In findVieById lateinit var likeCountTxt: TextView lateinit var likeBtn: Button

    override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) loveCountTxt = findViewById(R.id.txt_love_count) likeBtn = findViewById(R.id.btn_like) viewModel.likes.observe(this, Observer { likeCountTxt.text = "${it}" }) likeBtn.setOnClickListener { viewModel.onLike() } }
  9. In DataBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding

    : ActivityMainBinding = DataBindingUtil. setContentView(this, R.layout.activity_main) binding.lifecycleOwner = this binding.viewmodel = viewModel } <layout> <data> <variable name="viewmodel" type=".SampleViewModel" /> </data> <RelativeLayout <TextView android:text="@{Integer.toString(viewmodel.likes)}"/> <Button android:onClick="@{() -> viewmodel.onLike()}”/> </RelativeLayout> </layout>
  10. In ViewBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) var binding

    = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) viewModel.likes.observe(this, Observer { binding.count.text = "${it}" }) binding.like.setOnClickListener { viewModel.onLike() } }