Reputation: 963
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val myName:MyName = MyName("Kotlin noob")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.myName = myName //line 1
binding.doneButton.setOnClickListener {
addName(it)
}
}
fun addName(view: View) {
myName?.nickName = nickName_edit.text.toString() //line 2
binding.showNameTextView.text = "hello ${binding.enterNameEditText.text}"
binding.showNameTextView.visibility = View.VISIBLE
binding.enterNameEditText.visibility = View.GONE
view.visibility = View.GONE
}
//this is the class used for data
data class MyName(var name:String="", var nickName:String="")
}
how the commented code work ? i mean in line 1 how are we assigning myName to myName they are the same thing, and how we can assign reference variables to each ? and in line 2 what is that ? after myName
Upvotes: 0
Views: 144
Reputation: 1203
Bindings are generated in runtime from your xml file, in this case
R.layout.activity_main
First things first, if your layout had different name then the name of generated binding would also be different.
R.layout.activity_test // ActivityTestBinding
Now in your layout you have a view with identifier myName
. Thats why your generated class ActivityMainBinding
can find myName. So binding.myName
refers to an element in your xml while myName
refers to the object you created. This is more related to using databinding, you should do the identical thing when writing with Java as well.
?
is just an operator you can use with nullable objects. In java, you can write this
if(myName != null){
myName.nickName = nickName_edit.text.toString()
}
Upvotes: 1