Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom lint rule that prohibits requires instantiating AppCompat views when possible.
package com.lyft.android.lint.checks
import com.android.SdkConstants
import com.android.tools.lint.detector.api.*
import com.intellij.psi.PsiMethod
import org.jetbrains.uast.UCallExpression
class AppCompatViewConstructorDetector : Detector(), Detector.UastScanner {
companion object {
val ISSUE = Issue.create(
id = "AppCompatViewConstructor",
briefDescription = "AppCompat view constructor",
explanation = """
AppCompat views provide important bug fixes and backported features for earlier
platforms. Instead of instantiating `android.widget` classes directly,
instantiate the corresponding AppCompat view from `androidx.appcompat.widget` instead.
""",
implementation = Implementation(
AppCompatViewConstructorDetector::class.java,
Scope.JAVA_FILE_SCOPE
),
priority = 5,
category = Category.CORRECTNESS,
severity = Severity.ERROR
)
}
override fun getApplicableConstructorTypes() = listOf(
SdkConstants.FQCN_AUTO_COMPLETE_TEXT_VIEW,
SdkConstants.FQCN_BUTTON,
SdkConstants.FQCN_CHECK_BOX,
SdkConstants.FQCN_CHECKED_TEXT_VIEW,
SdkConstants.FQCN_EDIT_TEXT,
SdkConstants.FQCN_IMAGE_BUTTON,
SdkConstants.FQCN_IMAGE_VIEW,
SdkConstants.FQCN_MULTI_AUTO_COMPLETE_TEXT_VIEW,
SdkConstants.FQCN_RADIO_BUTTON,
SdkConstants.FQCN_RATING_BAR,
SdkConstants.FQCN_SEEK_BAR,
SdkConstants.FQCN_SPINNER,
SdkConstants.FQCN_TEXT_VIEW,
SdkConstants.FQCN_TOGGLE_BUTTON
)
override fun visitConstructor(
context: JavaContext,
node: UCallExpression,
constructor: PsiMethod
) {
val viewName = constructor.containingClass?.name
val appCompatViewName = "AppCompat$viewName"
val message = "This code should instantiate an instance of $appCompatViewName."
context.report(
issue = ISSUE,
scope = node,
location = context.getLocation(node),
message = message
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.