问题
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);
}
i get a ClassCastException
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)
回答1:
You are passing the Application Context
not the Activity Context
with
getApplicationContext();
Wherever you are passing it pass this
or ActivityName.this
instead.
Since you are trying to cast the Context
you pass (Application not Activity as you thought) to an Activity
with
(Activity)
you get this exception because you can't cast the Application to Activity
since Application is not a sub-class of Activity
.
回答2:
In my case, when I'm in an activity that extends from AppCompatActivity
, it did not work(Activity) getApplicationContext ()
, I just putthis
in its place.
来源:https://stackoverflow.com/questions/23546303/android-app-application-cannot-be-cast-to-android-app-activity