I have an Activity that adds a new view onPostCreate()
like so:
View rootView = findViewById(android.R.id.content);
((ViewGroup)rootView).addView(myView);
When this code runs, I get a NullPointerException
. However, if I don't cast it and check the output:
View rootView = findViewById(android.R.id.content);
Log.v(TAG, "rootView is " + rootView);
I get the log:
1340-1340/com.example.app V/MyActivity﹕ rootView is android.widget.FrameLayout@414d1b48
Why does this happen?
EDIT: I forgot to add that setContentView()
was called in the preceding onCreate()
and I did call super.onPostCreate()
before the cast
Casting is not a problem, or else a ClassCastException
would be thrown. It seems your myView
that you pass to addView(View view)
method is null, I don't see any other possibility. Make sure you've initialized myView
properly.
确保以下行中的myView
不为null:
((ViewGroup)rootView).addView(myView);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.