androidcompiler-errorsandroid-databindingnon-static

Android Data Binding Error : non-static variable R cannot be referenced from a static context


I got the following error while building my android project in the Layout Data Binding auto generated class

error: non-static variable R cannot be referenced from a static context View root = inflater.inflate(R.layout.rgb_input_layout, parent, false)

Here's my layout XML file that my project is binding:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="wrap_content"
    android:orientation="vertical"
    android:padding="12dp">


    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:layout_marginBottom="12dp"
        android:text="Please provide the color RGB values"
        android:textColor="#01031E"
        android:textSize="24sp"
        android:textStyle="bold" />

    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/R"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="R"
            android:inputType="number" />

        <EditText
            android:id="@+id/G"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="G"
            android:inputType="number" />

        <EditText
            android:id="@+id/B"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="B"
            android:inputType="number" />
    </LinearLayout>
</LinearLayout>

Solution

  • This is because you declared a view with the id R

    android:id="@+id/R"
    

    The auto-generated binding class stores the views in attributes named after their IDs.

    This means that when you have a view with the id="R" the binding class will automatically create an attribute R that causes a conflict with the static resources class R and you get this error.

    All you have to do is change the id to something else

            <EditText
                android:id="@+id/edittext_R"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:hint="R"
                android:inputType="number" />