溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Android代碼檢查規(guī)則Lint怎么自定義與應(yīng)用

發(fā)布時間:2022-04-12 13:41:44 來源:億速云 閱讀:404 作者:iii 欄目:開發(fā)技術(shù)

今天小編給大家分享一下Android代碼檢查規(guī)則Lint怎么自定義與應(yīng)用的相關(guān)知識點,內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。

前言:

在日常的代碼開發(fā)中,此處相信每個開發(fā)人員對代碼質(zhì)量都是高要求,有自己的一套代碼規(guī)范,但是我們不是單獨作戰(zhàn),往往大家都是團(tuán)隊作戰(zhàn),人是最大的變量,各人各異,如何保證團(tuán)隊的代碼質(zhì)量和代碼規(guī)范呢?靠開發(fā)者自覺嗎?也許有的團(tuán)隊有嚴(yán)格的CR機(jī)制,在MR階段會進(jìn)行CR,CR不通過的MR是不允許合入的,但是這樣會使Reviewer花費較多的時間去校驗,那么這時候我們就需要在編碼過程中提供一種代碼檢測機(jī)制。

例如:期望表現(xiàn)的效果就是在編碼時可以展示異常檢測的方法,高亮或者標(biāo)紅,當(dāng)鼠標(biāo)懸停在高亮的代碼上時,會提供問題的描述和解決方法。需要這種效果,就需要自定義lint了。

Android代碼檢查規(guī)則Lint怎么自定義與應(yīng)用

什么是Lint

在Android Studio中提供的代碼掃描工具Lint,可在無需實際執(zhí)行該應(yīng)用,也不必編寫測試用例的情況下幫助開發(fā)者發(fā)現(xiàn)代碼質(zhì)量問題和提出一些改進(jìn)建議。

Lint工具可檢查您的 Android 項目源文件是否包含潛在錯誤,以及在正確性、安全性、性能、易用性、便利性和國際化方面是否需要優(yōu)化改進(jìn)。在使用 Android Studio 時,配置的 Lint 和 IDE 檢查會在您每次構(gòu)建應(yīng)用時運行。不過,您可以手動運行檢查或從命令行運行 Lint。

android studio內(nèi)置了較多的lint規(guī)則,但內(nèi)置的lint規(guī)則無法滿足直觀的適合我們時,就需要我們自定義lint了。

Android代碼檢查規(guī)則Lint怎么自定義與應(yīng)用

自定義Lint流程:

1. 新創(chuàng)建module,Module類型選擇Java or Kotlin Library, 暫時命名lint_tools

2. 在build.gradle中引入lint的依賴

    dependencies {
        compileOnly 'com.android.tools.lint:lint-api:27.2.2'
        compileOnly 'com.android.tools.lint:lint-checks:27.2.2'
    }

在moudle中依賴了lint-api和lint-checks,其中l(wèi)int-api就是lint相關(guān)的api,lint-checks就是android studio里自定義的一些lint規(guī)則,我們自定義lint可以參考lint-checks里面的寫法。

3. 本地創(chuàng)建個資源id命名檢查規(guī)則,用來規(guī)范項目中的id統(tǒng)一命名

創(chuàng)建ViewIdDetector,直接繼承LayoutDetector(也可以繼承ResourceXmlDetector 或者 繼承Detector實現(xiàn)的接口是XmlScanner,方式多樣)

import com.android.SdkConstants
import com.android.tools.lint.detector.api.*
import com.android.tools.lint.detector.api.Category.Companion.CORRECTNESS
import com.android.tools.lint.detector.api.Scope.Companion.RESOURCE_FILE_SCOPE
import org.w3c.dom.Element

class ViewIdDetector : LayoutDetector() {
    
    override fun getApplicableElements(): Collection<String>? {
        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建議使用view的縮寫_xxx; ${element.tagName} 建議使用 `${expMsg}_xxx`"
                )
            }
        }
    }

    companion object {
        val ISSUE: Issue = Issue.create(
            "ViewIdCheck",
            "ViewId命名不規(guī)范",
            "ViewIdName建議使用 view的縮寫加上_xxx,例如tv_xxx, iv_xxx",
            CORRECTNESS,
            5, Severity.ERROR,
            Implementation(
                ViewIdDetector::class.java,
                RESOURCE_FILE_SCOPE
            )
        )
    }
}

自定義Detector可以實現(xiàn)一個或多個Scanner接口,選擇實現(xiàn)哪種接口取決于你想要的掃描范圍。
Lint API 中內(nèi)置了很多 Scanner:

Scanner 類型Desc
UastScanner掃描 Java、Kotlin 源文件
XmlScanner掃描 XML 文件
ResourceFolderScanner掃描資源文件夾
ClassScanner掃描 Class 文件
BinaryResourceScanner掃描二進(jìn)制資源文件
GradleScanner掃描Gradle腳本

4. 實現(xiàn)IssueRegistry并添加對應(yīng)的自定義Issue:

class IMockIssueRegistry: IssueRegistry() {
    override val issues: List<Issue>
        get() = listOf(
            ViewIdDetector.ISSUE
        )

}

5. 在module(lint_tools)中對應(yīng)的build.gradle中配置如下信息:

jar {
    manifest {
        attributes("Lint-registry-v2": "com.imock.lint.IMockIssueRegistry")
    }
}

6. 在需要進(jìn)行l(wèi)int檢查的module中或者app目錄現(xiàn)的build.gradle中引用對應(yīng)的lint_tools即可使用。

dependencies {
    lintChecks project(path: ':lint-tools')
}

至此你可以試著自己自定義Lint了,相關(guān)語法api都可參考lint-checks中提供的Detector實現(xiàn),來實現(xiàn)自己的Lint檢查規(guī)則。

拓展一下:

1. 針對Issue.create參數(shù)了解一下:

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
        )
    }
}
  • 參數(shù)id 唯一的id,簡要表面當(dāng)前提示的問題。

  • 參數(shù)briefDescription 簡單描述當(dāng)前問題

  • 參數(shù)explanation 詳細(xì)解釋當(dāng)前問題和修復(fù)建議

  • 參數(shù)category 問題類別

  • 參數(shù)priority 優(yōu)先級,從1到10,10最重要

  • 參數(shù)Severity 嚴(yán)重程度:FATAL(奔潰), ERROR(錯誤), WARNING(警告),INFORMATIONAL(信息性),IGNORE(可忽略)

  • 參數(shù)Implementation Issue和哪個Detector綁定,以及聲明檢查的范圍。Scope有如下選擇范圍:RESOURCE_FILE(資源文件),BINARY_RESOURCE_FILE(二進(jìn)制資源文件),RESOURCE_FOLDER(資源文件夾),ALL_RESOURCE_FILES(所有資源文件),JAVA_FILE(Java文件), ALL_JAVA_FILES(所有Java文件),CLASS_FILE(class文件), ALL_CLASS_FILES(所有class文件),MANIFEST(配置清單文件), PROGUARD_FILE(混淆文件),JAVA_LIBRARIES(Java庫), GRADLE_FILE(Gradle文件),PROPERTY_FILE(屬性文件),TEST_SOURCES(測試資源),OTHER(其他);

以上就是“Android代碼檢查規(guī)則Lint怎么自定義與應(yīng)用”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學(xué)習(xí)更多的知識,請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI