I am new to view binding. If I use findViewById and pass the data string data using intent's putExtra, everything is working fine. But it is not working with view Binding.
class MainActivity : AppCompatActivity() {
companion object{
const val camlinOrderKey = "com.example.mk_order.MainActivity.camlinOrderKey"
const val flairOrderKey = "com.example.mk_order.MainActivity.flairOrderKey"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var binding: ActivityMainBinding
binding = ActivityMainBinding.inflate(layoutInflater)
val eT1 = findViewById<EditText>(R.id.eT1)
// val eT2 = findViewById<EditText>(R.id.eT2)
val btnOrder = findViewById<Button>(R.id.btnOrder)
btnOrder.setOnClickListener {
val reviewIntent = Intent(this, ReviewOrder::class.java)
val camlinOrder = eT1.text.toString()
val flairOrder = binding.eT2.text.toString()
reviewIntent.putExtra(camlinOrderKey, camlinOrder)
reviewIntent.putExtra(flairOrderKey, flairOrder)
startActivity(reviewIntent)
}
}
}
The eT1 shows the data on new activity but eT2 is empty. There is no error. eT2 is empty. Can you help me find the error?
This issue occurs because you don't pass binding.root to setContentView method of activity and binding object has no reference to views in activity layout.
According to the view binding documentation :
To set up an instance of the binding class for use with an activity, perform the following steps in the activity's onCreate() method:
You should change your code to this :