View binding is a feature that makes it easier to write code and helps to find the id of the element of an XML file
Setup
goto the gradle (app) file and enable viewBinding
buildFeatures {
viewBinding true
}
use view Binding in activities
To set up an instance of the binding class for use with an activity perform the following steps in the activity's "onCreate()" method.
call the static "inflate()" method in the generated binding class. This creates an instance of the binding class for the activity to use
pass the root view to setOnClickListener() to make it the active view on the screen
private lateinit var binding: ResultProfileBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ResultProfileBinding.inflate(layoutInflater) val view = binding.root setContentView(view) }
Project implementation
create XML file
```xml <?xml version="1.0" encoding="utf-8"?>
2. create kotlin file
```kotlin
package com.example.learncode
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.learncode.databinding.ActivitySignupBinding
import com.google.firebase.auth.FirebaseAuth
lateinit var firebaseAuth: FirebaseAuth
private lateinit var binding: ActivitySignupBinding
class SignupActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= ActivitySignupBinding.inflate(layoutInflater)
setContentView(binding.root)
firebaseAuth= FirebaseAuth.getInstance()
binding.signupbtn.setOnClickListener {
signupUser()
}
binding.acsigntxt.setOnClickListener{
val intent = Intent(this,LoginActivity::class.java)
startActivity(intent)
finish()
}
}
private fun signupUser(){
val email = binding.signupemail.text.toString()
val password = binding.tvpassword1.text.toString()
val cpassword = binding.cpasswrd.text.toString()
//validation
if (email.isBlank()||password.isBlank()||cpassword.isBlank()){
return
}
if (password!=cpassword){
//Toast.makeText(this,"Password not mached",Toast.LENGTH_SHORT).show()
return
}
firebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this){
if(it.isSuccessful){
val i = Intent(this,MainActivity::class.java)
startActivity(i)
finish()
}else{
Toast.makeText(this,"Sign Up failed",Toast.LENGTH_SHORT).show()
}
}
}
}