Skip to content

Instantly share code, notes, and snippets.

@alexjlockwood
Created August 10, 2019 23:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexjlockwood/2a4a30df987de12a3c8eff1730d306d5 to your computer and use it in GitHub Desktop.
Save alexjlockwood/2a4a30df987de12a3c8eff1730d306d5 to your computer and use it in GitHub Desktop.
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