Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Layouts used by code generated with Data Binding incorrectly reported as UnusedResource by lint

Lint is considering layouts used by classes generated with Data Binding as unused, therefore triggering the corresponding UnusedResource warning.

For example:

../../src/main/res/layout/activity_start.xml:2: The resource R.layout.activity_start appears to be unused

despite there's a reference in one of the classes generated with Data Binding:

public static ActivityStartBinding inflate(android.view.LayoutInflater inflater, android.databinding.DataBindingComponent bindingComponent) {
    return bind(inflater.inflate(com.tuenti.messenger.R.layout.activity_start, null, false), bindingComponent);
}

Is there a way to make lint consider those generated classes in order to avoid these false positives?

like image 580
David Santiago Turiño Avatar asked Nov 10 '16 12:11

David Santiago Turiño


2 Answers

I've been looking into this and found a solution which allows for the use of generated classes.

First, you must add checkGeneratedSources = true to your lintOptions block. For example, inside your app module build.gradle:

android {
    lintOptions {
        checkDependencies = true
        checkGeneratedSources = true
    }
}

Lint should now include the generated source files and will no longer give false positives. You may run into additional issues where the generated files throw different errors, in my case some of the generated files related to Room were violating the RestrictedApi rule. If that's the case, simply add a rule to the lint.xml to exclude that rule from running on the generated code like so:

<issue id="RestrictedApi" severity="error">
    <ignore path="build" />
</issue>
like image 99
jbutton Avatar answered Oct 15 '22 19:10

jbutton


I had the same issue, and worked around it by using the DataBindingUtil helper instead of the generated class. You can use it that way:

binding = DataBindingUtil.inflate(inflater, R.layout.activity_start, container, false)

Note that it will return a ActivityStartBinding and not a generic object, which is exactly what you want. And as your layout is used directly from your code and not from generated code, there's no issue with Lint anymore.

like image 23
Marc Plano-Lesay Avatar answered Oct 15 '22 19:10

Marc Plano-Lesay