android - Activity、AppCompatActivity、FragmentActivity和ActionBarActivity : When to Use Which?

标签 android android-fragments android-activity android-actionbaractivity appcompatactivity

我来自 iOS,这很容易,您只需使用 UIViewController。然而,在 Android 中,事情似乎要复杂得多,某些 UIComponents 用于特定的 API 级别。我正在阅读适用于 Android 的 BigNerdRanch(这本书大约有 2 年的历史),他们建议我使用 Activity 来托管我的 FragmentActivities。但是,我认为 Activity 已被弃用。

那么对于 API 级别 22(至少支持 API 级别 15 或 16),我究竟应该使用什么来托管组件和组件本身?所有这些都有用吗,还是我应该几乎只使用一两个?

最佳答案

I thought Activity was deprecated

没有。

So for API Level 22 (with a minimum support for API Level 15 or 16), what exactly should I use both to host the components, and for the components themselves? Are there uses for all of these, or should I be using one or two almost exclusively?

Activity 是基线。每个 Activity 都直接或间接地从 Activity 继承。

FragmentActivity 用于在 support-v4support-v13 库中找到的 fragment 的反向移植。在 API 级别 11 中添加了 fragment 的 native 实现,它低于您建议的 minSdkVersion 值。您需要特别考虑 FragmentActivity 的唯一原因是,如果您想使用嵌套 fragment (一个 fragment 包含另一个 fragment ),因为在 API 级别 17 之前, native fragment 不支持这一点。

AppCompatActivity 来自 appcompat-v7 库。原则上,这提供了操作栏的反向移植。由于在 API 级别 11 中添加了 native 操作栏,因此您不需要 AppCompatActivity 。然而,当前版本的 appcompat-v7 在操作栏和各种小部件方面也添加了 Material Design 美学的有限向后移植。使用 appcompat-v7 有利有弊,远远超出了这个特定 Stack Overflow 答案的范围。

ActionBarActivityappcompat-v7 中基础 Activity 的旧名称。由于种种原因,他们想改名。除非您使用的某些第三方库坚持使用 ActionBarActivity,否则您应该更喜欢 AppCompatActivity 而不是 ActionBarActivity

因此,鉴于您的 minSdkVersion 在 15-16 范围内:

  • 如果您想要向后移植的 Material Design 外观,请使用 AppCompatActivity

  • 如果没有,但你想要嵌套 fragment ,使用 FragmentActivity

  • 如果没有,使用Activity

只需在注释中添加注释:AppCompatActivity 扩展 FragmentActivity,因此任何需要使用 FragmentActivity 功能的人都可以使用 AppCompatActivity .

关于android - Activity、AppCompatActivity、FragmentActivity和ActionBarActivity : When to Use Which?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31297246/

相关文章:

android - toast 重力产生不正确的垂直位置

android - 如何在 Android 中发送电子邮件?

安卓支持unicode吗?

java.lang.ClassCastException : CLASS/Activity cannot be cast to MainActivity

android - 从子 Activity 调用父 Activity 中的函数 - Android

android - 将 PhoneGap Build App 部署到 Google Play 商店 : Multiple Keys?

android - ViewPager - 第一个 fragment 总是在不在 View 中时重新创建( onPause -> onStop -> onAttach->...onResume )

Android 谷歌地图 CameraUpdateFactory 未初始化

java - Android:你如何通过点击进入另一个 Activity ?

android - 通过 startActivityForResult 重用两个 Activity 中的 Activity