android.app.Application 无法转换为 android.app.Activity [英] android.app.Application cannot be cast to android.app.Activity
问题描述
我正在尝试从另一个类更改 LinearLayout
,但是当我运行此代码时:
I'm trying to change a LinearLayout
from another class, but when i run this code:
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 是扩展通过 getApplicationContext() 传递的 Activity
的主要活动;
context is the Main activity that extends Activity
passed with a 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)
推荐答案
您传递的是 Application Context
而不是 Activity Context
与
You are passing the Application Context
not the Activity Context
with
getApplicationContext();
无论你在哪里传递它,都通过 this
或 ActivityName.this
代替.
Wherever you are passing it pass this
or ActivityName.this
instead.
由于您试图将 Context
传递给 Activity
与
Since you are trying to cast the Context
you pass (Application not Activity as you thought) to an Activity
with
(Activity)
你得到这个异常是因为你不能将 Application 转换为 Activity
因为 Application 不是 Activity
的子类.
you get this exception because you can't cast the Application to Activity
since Application is not a sub-class of Activity
.
这篇关于android.app.Application 无法转换为 android.app.Activity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!