gpt4 book ai didi

android - 为什么 Android 使用多个上下文并且每个上下文都不同?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:08:20 26 4
gpt4 key购买 nike

我知道android中有很多这样的context

  1. 申请
  2. Activity
  3. 服务
  4. 内容提供者
  5. 广播接收者

所以当我创建一个 new TextView 时,我必须像这样在构造函数中传递 context

TextView textView = new TextView(this);

我知道它是必需的,但为什么不直接创建并让 android 为我处理上下文呢?

最佳答案

我喜欢从视觉上考虑 context,因为我是 Fragments 的狂热用户,所以大多数时候我会传递一个 context ,或继承一个 context 实例,它通常来自 Activity

Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

Android Developers 所述.它基本上为您提供了帮助,确保您可以执行“应用程序级操作的向上调用”,所以让我们在您的案例中详细说明这一点。

I know it is needed BUT why not just be created and android handle the context for me ?

TextView 的新实例,创建时没有 Context 实例。所以它看起来像 TextView tv = new TextView(); 会让 Android 混淆 TextView 的生成位置。他们如何知道这是应用程序级别还是 Activity 级别?在创建实例之前,TextView 需要哪些特征?当您转到 TextView 的构造函数时,您会注意到它在生成上述 TextView 的新实例之前如何需要一些重要信息。例如:final Resources.Theme theme = context.getTheme(); 只是他们通过 Context 实例收集信息的一行,现在他们知道信息来自哪里来自,然后他们可以应用相应的主题。

Android 将如何知道您从何处调用该类以及您希望将其应用到哪个主题,除非您告诉他们?

最后回答你的问题,“为什么不直接创建 android 来为我处理上下文?” 这个 android 为你处理事情,但它需要知道你从哪里来,你在生命周期的哪个阶段。

编辑:从评论中添加。

why not that theme initialized in the application context and used in the code of the textview without my interference

因为它再次归结为您希望该小部件所基于的位置。所以假设我想要一个 TextView 在我的 activity 中,但我们正在调用应用程序级上下文,自动应用的主题将是 @style/应用主题。但是,如果我希望 TextView 在当前 activity 中遵循相同的样式指南,而不是手动更改我想创建的每个小部件的主题(我是开发人员)android无论您在应用程序中的哪个位置,它都会为您处理。它使样式更简单,创建 TextView 的新实例简单等等

you know i remember a scenario from .NET platform when i create new button on the form and without any thing passed to the constructor it inherits its theme for the parent form automatically .. you think .NET design is better on this or what?

不幸的是,我没有使用 .NET 的经验,但我认为在使用可以随时关闭和打开的应用程序期间, Activity 、服务和接收器的状态不断变化。这是一个很好的功能,可以确保 Android 知道你在哪里,以及你正在创建什么。

关于android - 为什么 Android 使用多个上下文并且每个上下文都不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41260856/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com