关于Support库28及以上版本无法查看源码问题

2,608 阅读2分钟

声明

不知道大家有没有注意到这么个问题:

在最新创建项目的时候,有了 User androidx.* artifacts 这样一个选项。可能你还不知道 androidx 的意思,可以这样理解,androidx 代替了之前的一系列的 support 库。如果你选择了 androidx 就表示在你新创建的项目里面使用的支持库就是 androidx 了而不是之前我们用的 support 类型的支持库了。

假设这里不勾选那么就说明我们依然使用之前的 android.support.* 这种类型的支持库,比如implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' 等等。

这个时候你新建的项目如果编译的时候用的 api 28,也就是在build.gradle 中是 compileSdkVersion 28 这个是你会发现,当你查看 support 库中的代码的时候没法看了,变成下面这样了

没法看源码了,只能看到 .class 了。这是因为:

在 Android 28.0.0 已经没有给 Support Library 28.0.0 提供源码查看了,即便我们使用了 Android 28 进行编译项目,用了 Support Library 28.0.0,这个时候当你查看 Support Library 中的类的时候会发现无法查看源码,看到的只是 xxx.class 。这是因为在 Android9.0(API 级别 28)发布后,新版本支持库 AndroidX 随之诞生了,它属于 JetPack,除了包含了原先支持库中的内容,还包含了最新的 JetPack 组件。

在使用 api 28 的时候我们仍然可以继续使用支持库,不过所有的新库的开发都在 androidx 中进行了,因此我们是看不到源码的(之前的版本是可以看到源码的),Google 建议所有的新项目使用 androidx 库。

因此解决方案

拥抱 androidx 库,这也是 Google 所推荐的

另外一个方法就是使用 28 以下的版本来进行编译:比如:

  compileSdkVersion 26
  dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

这样是仍然可以查看 support 中类的源代码的。