Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to customize and apply Android Code Inspection rules Lint

2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Today, I would like to share with you the relevant knowledge points about how to customize and apply Android code inspection rules Lint. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article.

Foreword:

In daily code development, it is believed that every developer has high requirements for code quality and has his own set of code specifications, but we do not fight alone, often we all fight as a team, people are the biggest variables, and each person is different. how to ensure the code quality and code norms of the team? Does it depend on the developer's consciousness? Maybe some teams have a strict CR mechanism, and it is not allowed to integrate MR that fails CR,CR in the MR phase, but it will take more time for Reviewer to verify, so we need to provide a code detection mechanism in the coding process.

For example, the desired effect is to show the method of exception detection, highlight or red, when coding, and provide a description and solution to the problem when the mouse hovers over the highlighted code. If you want this effect, you need to customize the lint.

What is Lint?

The code scanning tool Lint provided in Android Studio can help developers find code quality problems and put forward some suggestions for improvement without actually executing the application or writing test cases.

The Lint tool checks to see if your Android project source files contain potential errors and whether improvements are needed in terms of correctness, security, performance, ease of use, convenience, and internationalization. When using Android Studio, the configured Lint and IDE checks run each time you build the application. However, you can run the check manually or run Lint from the command line.

Android studio has more built-in lint rules, but the built-in lint rules are not intuitive enough to suit us, so we need to customize lint.

Custom Lint process: 1. Select Java or Kotlin Library for the newly created module,Module type, and temporarily name lint_tools2. Introduce lint's dependency dependencies {compileOnly 'com.android.tools.lint:lint-api:27.2.2' compileOnly' com.android.tools.lint:lint-checks:27.2.2'} into build.gradle

In moudle, we rely on lint-api and lint-checks, where lint-api is lint-related api,lint-checks is some of the custom lint rules in android studio. We can refer to the writing method in lint-checks for custom lint.

3. Create a resource id naming check rule locally, which is used to standardize the unified naming of id in the project

Create ViewIdDetector and directly inherit LayoutDetector (you can also inherit ResourceXmlDetector or inherit the interface of Detector implementation is XmlScanner in various ways)

Import com.android.SdkConstantsimport com.android.tools.lint.detector.api.*import com.android.tools.lint.detector.api.Category.Companion.CORRECTNESSimport com.android.tools.lint.detector.api.Scope.Companion.RESOURCE_FILE_SCOPEimport org.w3c.dom.Elementclass ViewIdDetector: LayoutDetector () {override fun getApplicableElements (): Collection? {return listOf (SdkConstants.TEXT_VIEW, SdkConstants.IMAGE_VIEW) SdkConstants.BUTTON)} override fun visitElement (context: XmlContext, element: Element) {if (! element.hasAttributeNS (SdkConstants.ANDROID_URI, SdkConstants.ATTR_ID)) {return} val attr = element.getAttributeNodeNS (SdkConstants.ANDROID_URI) SdkConstants.ATTR_ID) val value = attr.value if (value.startsWith (SdkConstants.NEW_ID_PREFIX)) {val idValue = value.substring (SdkConstants.NEW_ID_PREFIX.length) var matchRule = true var expMsg = "" when (element.tagName) {SdkConstants.TEXT_VIEW-> {expMsg = "tv" matchRule = idValue.startsWith (expMsg)} SdkConstants.IMAGE_VIEW-> {expMsg = "iv" matchRule = idValue.startsWith (expMsg)} SdkConstants.BUTTON-> {expMsg = "btn" MatchRule = idValue.startsWith (expMsg)}} if (! matchRule) {context.report (ISSUE) Attr, context.getLocation (attr), "ViewIdName recommends using the abbreviation _ xxx of view ${element.tagName} is recommended to use `${expMsg} _ xxx` ")}} companion object {val ISSUE: Issue = Issue.create (" ViewIdCheck "," ViewId naming is not standard "," ViewIdName recommends using the abbreviation of view plus _ xxx, such as tv_xxx, iv_xxx ", CORRECTNESS 5, Severity.ERROR, Implementation (ViewIdDetector::class.java, RESOURCE_FILE_SCOPE)}}

Custom Detector can implement one or more Scanner interfaces, and which interface to implement depends on the scan range you want.

There are a lot of Scanner built into Lint API:

Scanner type DescUastScanner scan Java, Kotlin source file XmlScanner scan XML file ResourceFolderScanner scan resource folder ClassScanner scan Class file BinaryResourceScanner scan binary resource file GradleScanner scan Gradle script 4. Implement IssueRegistry and add the corresponding custom Issue:class IMockIssueRegistry: IssueRegistry () {overrideval issues: List get () = listOf (ViewIdDetector.ISSUE)} 5. Configure the following information in the corresponding build.gradle in module (lint_tools): jar {manifest {attributes ("Lint-registry-v2": "com.imock.lint.IMockIssueRegistry")} 6. You can use it by referencing the corresponding lint_tools in the module that needs to be checked for lint or in the current build.gradle in the app directory. Dependencies {lintChecks project (path:': lint-tools')}

At this point, you can try to customize your own Lint. The relevant syntax api can refer to the Detector implementation provided in lint-checks to implement your own Lint checking rules.

Expand: 1. Learn about the Issue.create parameter: companion object {/ * Creates a new issue. The description strings can use some simple markup; * see the [TextFormat.RAW] documentation * for details. * * @ param id the fixed id of the issue * @ param briefDescription short summary (typically 5-6 words or less), typically * describing the * * problem** rather than the * * fix** * (e.g. "Missing minSdkVersion") * @ param explanation a full explanation of the issue, with suggestions for * how to fix it * @ param category the associated category, if any * @ param priority the priority, a number from 1 to 10 with 10 being most * important/severe * @ param severity the default severity of the issue * @ param implementation the default implementation for this issue * @ return a new [Issue] * / @ JvmStatic fun create (id: String BriefDescription: String, explanation: String, category: Category, priority: Int, severity: Severity, implementation: Implementation): Issue {val platforms = computePlatforms (null, implementation) return Issue (id, briefDescription, explanation, category, priority, severity, platforms, null, implementation)}}

Parameter id unique id, a brief description of the question currently prompted on the surface.

The parameter briefDescription briefly describes the current problem

Parameter explanation explains the current problem and repair recommendations in detail

Parameter category problem category

Parameter priority priority, from 1 to 10 is the most important.

Parameter Severity severity: FATAL (rout), ERROR (error), WARNING (warning), INFORMATIONAL (informational), IGNORE (negligible)

The parameter Implementation Issue is bound to which Detector, and the scope of the declaration check is declared. Scope has the following choices: RESOURCE_FILE (resource files), BINARY_RESOURCE_FILE (binary resource files), RESOURCE_FOLDER (resource folders), ALL_RESOURCE_FILES (all resource files), JAVA_FILE (Java files), ALL_JAVA_FILES (all Java files), CLASS_FILE (class files), ALL_CLASS_FILES (all class files), MANIFEST (configuration manifest files), PROGUARD_FILE (obfuscation files), JAVA_LIBRARIES (Java library) GRADLE_FILE (Gradle file), PROPERTY_FILE (properties file), TEST_SOURCES (test resource), OTHER (other)

These are all the contents of this article entitled "how to customize and apply Android Code Review rules Lint". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report