-1
When you create an Activity, there is the option to create it together with the layout, then Binding is automatic. After creating just put id on the components of this layout and use them in the code of Activity itself, for example:
If in your xml there is a Button with id "btnSalvar", in your Activity just write this btnSalvar inside some method (can be from onCreate) and put for example: btnSalvar.setOnClickListener{ thing you want the button to do when clicked }. Then the name btnSalvar will be in red to import, then just press Alt Enter to import.
The same thing is true for a Textview, which would be by . text, thus getting the text inside it.
class Main2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
btnSalvar.setOnClickListener{
var destreza = editDestreza.text
var inteligencia = editInteligencia.text
var sabedoria = editSabedoria.text
var forca = editForca.text
}
}
}
editDestreza, editInteligencia, editSabedoria and editForca are the ids of each Edittext in xml layout
Where is this option to create it together with the layout?
– Pedro Tavares
when you create the Activity appears the Generate Layout File option
– Elias
But this layout has already been generated like this.
– Pedro Tavares
Yes, but Activity by default already communicates with the layout through setContentView, which in its code is removed and would be in the line of val Binding :Create your character. I will edit my answer to clarify what is happening
– Elias
Another thing, inside your xml has to have a tools:context=". nameDaSuaActivity" to occur Binding, otherwise the application will crash. Esse tools:context=". nameSuaActivity" would be a property of the Layout component, can be below android:layout_height="match_parent" only before the arrow ">"
– Elias
val editDestreza : EditText = findViewById(R.id.editDestreza)
Se eu quiser referenciar o editText editDestreza eu preciso fazer isso, caso contrário dá Unresolved Reference.
– Pedro Tavares
Yes, it is because there is no setContentView of Activity itself, as written in my code.
– Elias
In my code for example I did not need to use findViewById(R.id.btnSalvar), I just used btnSalvar loose, what happens is that this btnSalvar will be painted red, because it was not imported yet the layout, then just click on btnSalvar and hit Alt Enter that imports the layout automatically
– Elias
Dude, if I were you would create another project from scratch with an Empty Activity, after that just put an Edittext in the layout and inside it put an id, that would be like android:id="@+id/edt_Destreza" Ai then writes "edt_Destreza" inside your Activity in onCreate . That alone will automatically identify the component. This edt_Destreza that you just wrote will be written in red, then just put your mouse on top and choose the import option
– Elias