androidkotlingradlelayout-inflaterandroid-viewbinding

What is the cause and sol to the error showing due to view Binding?


On Clicking the btnBmi button, the app is crashing, & in the logcat the error showing for binding code.

I have added the code in the build.gradle file and synced it.

buildFeatures {
    viewBinding true
}

// Code for .kt file.

package com.nandini.android.workoutapp

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.nandini.android.workoutapp.databinding.ActivityBmiCalculatorBinding

class BmiCalculatorActivity : AppCompatActivity() {

    private var binding: ActivityBmiCalculatorBinding?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding= ActivityBmiCalculatorBinding.inflate(layoutInflater)
        setContentView(binding?.root)

        setSupportActionBar(binding?.toolbarBmi)
        if(supportActionBar!=null){
            supportActionBar?.setDisplayHomeAsUpEnabled(true)
            supportActionBar?.title="Calculate BMI"
        }
        binding?.toolbarBmi?.setNavigationOnClickListener {
            onBackPressed()
        }

    }
}

The button to jump on this activity is in the activity_main.xml file with id : btnBmi , & intent code in the MainActivity.kt file.

// in the onCreate method of MainActivity.kt file.

binding?.btnBmi?.setOnClickListener{
        val intent = Intent(this@MainActivity,BmiCalculatorActivity::class.java)
        startActivity(intent)}

Solution

  • Step 1 change the Parent Theme in the style.xml/theme.xml-

    parent="Theme.MaterialComponents.Light.NoActionBar"
    

    Step 2 - Add toolbar in activity_bmi_calculator.xml

     <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"       
            app:navigationIcon="@drawable/ic_home_black_24dp" />
    

    Step 3

    class BmiCalculatorActivity
        : AppCompatActivity() {
    
        lateinit var binding: ActivityBmiCalculatorBinding
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            binding = ActivityBmiCalculatorBinding.inflate(layoutInflater)
            setContentView(binding.root)
            binding.toolbar.title = "Calculate BMI"
            binding.toolbar.setNavigationOnClickListener {
                onBackPressed()
            }
    
        }