Remove findViewById in Kotlin-Android

Remove findViewById in Kotlin

From the newbie to the oldest developers in Android development knows the use of findViewById(). It is by far the commonest method used. When using this we associate a link between the XML view to the object view in Java file. Let me remind the terminology for this, well this exactly what we refer to as View Binding. 

In Kotlin, view binding is far more feasible and easy, as we got here a new plugin to add, and whoosh no findViewById() to remember every time we create a new view object. All you need to do is add a line in your 'build.gradle' file and its done. 

 apply plugin: 'kotlin-android-extensions'  

Now, how do we use this?

 import kotlinx.android.synthetic.main.activity_main.*  
 class MainActivity : AppCompatActivity() {  
   override fun onCreate(savedInstanceState: Bundle?) {  
     super.onCreate(savedInstanceState)  
     setContentView(R.layout.activity_main)  
     btnNextScreen.setOnClickListener{  
       val intent = Intent(this, NextActivity::class.java)  
       startActivity(intent)  
     }  
   }  
 }  

To able to use it easily we require an import. The one mentioned above, however in Android Studio it is auto-imported. Well  if you notice the layout name and the last part in the import are same. In this case it is 'activity_main'. I assume here that it mainly associates 'activity_main' to 'MainActivity', thus creating a cache of the view.
Lets see how the XML part looks and how we can render the view without id.


 <?xml version="1.0" encoding="utf-8"?>  
 <android.support.constraint.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">  
   <Button  
     android:id="@+id/btnNextScreen"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Next Screen!"  
     app:layout_constraintBottom_toBottomOf="parent"  
     app:layout_constraintLeft_toLeftOf="parent"  
     app:layout_constraintRight_toRightOf="parent"  
     app:layout_constraintTop_toTopOf="parent" />  
 </android.support.constraint.ConstraintLayout>  

Focus on the 'id' of the 'Button'  here, you will notice that its same as 'Button' name in Kotlin file. All the properties of the Button can be accessed by that particular id/name whatever you want to call it. So actually this can't get any easier than this.
If you are looking for a full project click here.

Comments

Popular posts from this blog

The var & val Of Kotlin

Kotlin Beginners Guide