gpt4 book ai didi

android - Android项目库中的类扩展应用程序?

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

我有一个项目(在 Eclipse 中),我已经把它变成了一个 Android 项目库,以便在另一个类似的项目中重用一些代码。我想我已经搬起石头砸自己的脚了,但是我遇到了错误:

Unable to start activity ComponentInfo{com.test.scroller1/com.lib.scrolltest.ScrollTestActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to com.lib.scrolltest.resAppVars

com.lib.scrolltest 是我的项目库,它实例化了一个扩展应用程序 (resAppVars) 的类。在我调用的 onCreate() 方法中:

mRav = (resAppVars) getApplicationContext ();

这样,我可以在 mRav 对象中使用方法,否则这些方法在其他类中会是很多重复代码(例如将查询传递给返回结果 ArrayList 的通用选择语句)。

这里有什么问题?看来我在实现 Application 类的方式上遇到了限制。

最佳答案

调用 getApplicationContext() 返回 Application当前应用程序的对象(即拥有 onCreate() 正在其中运行的 Activity 的应用程序)。

除非你在做一些奇怪的事情,否则你无法选择哪个 Application使用类。 Application 的文档中甚至有一条注释说不要这样做:

There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

您应该只在您的库项目中创建一个常规共享类。或者,如果您不需要库项目提供的特殊功能,您也可以只使用常规 .jar 文件。

如果您需要共享状态,只需将其设为单例即可。 ;)

关于android - Android项目库中的类扩展应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8649866/

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