是否需要导入 support-v4 和 appcompat-v7 才能使用它们?

Is necessary to import support-v4 and appcompat-v7 to use them?

我正在使用 AppCompatActivity 和其他一些东西,例如片段等...这些是我的 activity:

的一些导入
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;

我从 google 示例中复制了这些依赖项:

dependencies {
    compile 'com.google.android.gms:play-services-ads:9.4.0'
    compile 'com.android.support:support-v4:23.1.1'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'
}

现在我正在尝试删除它们,我注意到我可以删除这些:

compile 'com.android.support:support-v4:23.1.1'
compile 'com.android.support:appcompat-v7:23.4.0'

删除它们,我的项目完美运行...为什么?

我正在编译:

compileSdkVersion 23
buildToolsVersion "23.0.3"
minSdkVersion 14
targetSdkVersion 22

支持设计库本身依赖于 appcompat-v7 和 support-v4 库。因此,您删除的显式依赖项将作为传递依赖项自动引入。 运行 ./gradlew app:dependencies 证实了这一点:

_releaseCompile - ## Internal use, do not manually configure ##
+--- com.android.support:design:23.4.0
|    +--- com.android.support:recyclerview-v7:23.4.0
|    |    +--- com.android.support:support-annotations:23.4.0 -> 24.0.0
|    |    \--- com.android.support:support-v4:23.4.0 -> 24.0.0 (*)
|    +--- com.android.support:appcompat-v7:23.4.0 -> 24.0.0
|    |    +--- com.android.support:support-v4:24.0.0 (*)
|    |    +--- com.android.support:support-vector-drawable:24.0.0
|    |    |    \--- com.android.support:support-v4:24.0.0 (*)
|    |    \--- com.android.support:animated-vector-drawable:24.0.0
|    |         \--- com.android.support:support-vector-drawable:24.0.0 (*)
|    \--- com.android.support:support-v4:23.4.0 -> 24.0.0 (*)

在您的 build.gradle 文件中显式声明这些依赖项(解释链接的答案)通常仍被认为是 good practice

If your project has direct dependencies on "B" then you should declare "B" as an explicit dependency even if "B" is a transitive dependency of some other explicit dependency "A". Future versions of "A" may no longer depend on "B", and updating to one of these versions of "A" would break your build.