Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element data is not allowed here in Android Studio data binding

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?

like image 777
FullStackOverflowDev Avatar asked Jan 04 '18 20:01

FullStackOverflowDev


1 Answers

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.

like image 107
George Mount Avatar answered Oct 20 '22 05:10

George Mount