android.app.Application 无法转换为 android.app.Activity

新手上路,请多包涵

我正在尝试从另一个类更改 LinearLayout ,但是当我运行此代码时:

 public class IRC extends PircBot {

ArrayList<String> channels;
ArrayList<Integer> userCount;
ArrayList<String> topics;

LinearLayout channelLayout;
Context context;

public IRC(Context ctx) {
    this.setName("xxxx");
    channels = new ArrayList<String>();
    userCount = new ArrayList<Integer>();
    topics = new ArrayList<String>();

    context = ctx;

    channelLayout = (LinearLayout) ((Activity) context).findViewById(R.id.channels);
}

我得到一个 ClassCastException

context 是扩展 Activity 的主要活动,通过 getApplicationContext();

LOGCAT

 05-08 17:53:55.102    3736-3799/g.d.allinonechat E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-5357
java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
        at g.d.xxx.IRC.<init>(IRC.java:34)
        at g.d.xxx.MainActivity$1.run(MainActivity.java:49)
        at java.lang.Thread.run(Thread.java:856)

原文由 DomeWTF 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

您正在传递应用程序 Context 而不是 Activity Context

 getApplicationContext();

无论您在哪里通过它,都通过 thisActivityName.this 代替。

由于您正在尝试投射 Context 您将(应用程序而不是您认为的活动)传递给 Activity

(Activity)

您收到此异常是因为您无法将 Application 转换为 Activity 因为 Application 不是 Activity 的子类。

原文由 codeMagic 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您的项目使用匕首,然后出现此错误,您可以在 android 清单中添加它

   <application
        ...
        android: name = ".BaseApplication"
        ...> ...

原文由 Tri yulianto 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题