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

2023-12-07

我正在尝试改变一个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);
}

i get a ClassCastException

上下文是扩展的主要活动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)

您正在通过申请Context不是Activity Context with

getApplicationContext();

无论你经过哪里,它都会过去this or ActivityName.this反而。

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

(Activity)

您收到此异常是因为您无法将应用程序转换为Activity因为应用程序不是子类Activity.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

android.app.Application 无法转换为 android.app.Activity 的相关文章

随机推荐