I'm trying to make a kind of tick-tac-toe android app (though with a 4x4 grid). I decided using buttons to depict each grid square and wanted to use data bindings to bind the text on the buttons to data from a String[][] array that would represent the grid internally. I tried doing something similar to what was presented here http://www.vogella.com/tutorials/AndroidDatabinding/article.html so I created this class:
public class ModelJoc extends BaseObservable{
private String[][] tabla_joc;
public ModelJoc() {
for (String[] line : tabla_joc)
for (String element : line)
element = "";
tabla_joc[0][0] = "M";
tabla_joc[0][1] = "W";
}
And then added the data binding to the activity_main.xml:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.tgeorge.temajoc.MainActivity">
<data>
<variable
name="state"
type="com.example.tgeorge.temajoc.ModelJoc"/>
</data>
And then tried to set the text of a button to a value from the array:
<Button
android:id="@+id/button1"
android:layout_width="50dp"
android:layout_height="50dp"
android:text="@={state.getBlockState()[0][0]}"/>
But it gives me these errors: "Element data is not allowed here" as well as "Attribute is missing the android: prefix". I can't tell what I'm doing wrong from the example in the tutorial so the question is where exactly should I be putting these?
I think I see the problem now. You must outline your layout with a <layout>
tag:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.tgeorge.temajoc.MainActivity">
<data>
<variable
name="state"
type="com.example.tgeorge.temajoc.ModelJoc"/>
</data>
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- ... -->
<Button
android:id="@+id/button1"
android:layout_width="50dp"
android:layout_height="50dp"
android:text="@{state.getBlockState()[0][0]}"/>
If you don't do that, android data binding won't recognize it as a data bound layout file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With