Android Studio Data Binding (bind) does not allow element data here
I’m trying to make a tick-tac-toe android app (albeit using a 4×4 grid). I decided to use the button to depict each grid square block and wanted to use data binding (bind) on the button to the data in a String[][] array that would represent the grid internally. I try to do something similar to the one 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";
}
Then add data binding (bind) to 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>
Then try setting the text of the button to a value in 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” and “Attribute is missing android: prefix”. I can’t tell from the examples in the tutorial what I’m doing wrong, so the question is where should I put them?
Solution
I
think I understand the problem now. You must use <layout>
to outline your layout label:
<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, Android Data Binding (BIND) will not recognize it as a Data Binding (BIND) layout file.