天天看點

android 修改xml節點,Android筆記(十六):Gradle腳本動态修改AndroidManifest.xml的MainActivity...

在主子產品build.gradle添加如下代碼即可修改AndroidManifest.xml的MainActivity,sync項目的時候就會執行

原理:利用Groovy XmlSlurper來改寫xml檔案

import groovy.xml.XmlUtil

this.afterEvaluate {

def manifestFile = "${projectDir}/src/main/AndroidManifest.xml

def xml = file(manifestFile)

def manifest = new XmlSlurper().parse(manifestFile)

def application = manifest.application

application.activity.each {

def isFind = false

it.children().each {

if(it.name() == "intent-filter"){

it.children().each{

if(it.name()=="action" &&

it.@"android:name"=="android.intent.action.MAIN"){

isFind = true

return true

}

}

}

if(isFind){

return true

}

}

if (isFind){

it.@"android:name" = "New Activity"

return true

}

}

xml.withWriter {out->

XmlUtil.serialize(manifest, out)

}

}

注:

${projectDir} :build.gradle的路徑

isFind:标志是否找到MainActivity所在的activity節點

XmlUtil.serialize:儲存修改後的xml檔案

本文位址:https://blog.csdn.net/weixin_40855673/article/details/108977416