Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems creating a Popup Window in Android Activity

I'm trying to create a popup window that only appears the first time the application starts. I want it to display some text and have a button to close the popup. However, I'm having troubles getting the PopupWindow to even work. I've tried two different ways of doing it:

First I have an XML file which declares the layout of the popup called popup.xml (a textview inside a linearlayout) and I've added this in the OnCreate() of my main Activity:

PopupWindow pw = new PopupWindow(findViewById(R.id.popup), 100, 100, true);     pw.showAtLocation(findViewById(R.id.main), Gravity.CENTER, 0, 0); 

Second I did the exact same with this code:

final LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);     PopupWindow pw = new PopupWindow(inflater.inflate(R.layout.popup, (ViewGroup) findViewById(R.layout.main) ), 100, 100, true);     pw.showAtLocation(findViewById(R.id.main_page_layout), Gravity.CENTER, 0, 0); 

The first throws a NullPointerException and the second throws a BadTokenException and says "Unable to add window -- token null is not valid"

What in the world am I doing wrong? I'm extremely novice so please bear with me.

like image 639
Amplify91 Avatar asked Nov 15 '10 18:11

Amplify91


2 Answers

To avoid BadTokenException, you need to defer showing the popup until after all the lifecycle methods are called (-> activity window is displayed):

 findViewById(R.id.main_page_layout).post(new Runnable() {    public void run() {      pw.showAtLocation(findViewById(R.id.main_page_layout), Gravity.CENTER, 0, 0);    } }); 
like image 162
kordzik Avatar answered Oct 22 '22 06:10

kordzik


Solution provided by Kordzik will not work if you launch 2 activities consecutively:

startActivity(ActivityWithPopup.class); startActivity(ActivityThatShouldBeAboveTheActivivtyWithPopup.class); 

If you add popup that way in a case like this, you will get the same crash because ActivityWithPopup won't be attached to Window in this case.

More universal solusion is onAttachedToWindow and onDetachedFromWindow.

And also there is no need for postDelayed(Runnable, 100). Because this 100 millis does not guaranties anything

@Override public void onAttachedToWindow() {     super.onAttachedToWindow();     Log.d(TAG, "onAttachedToWindow");      showPopup(); }  @Override public void onDetachedFromWindow() {     super.onDetachedFromWindow();     Log.d(TAG, "onDetachedFromWindow");      popup.dismiss(); } 
like image 38
Danylo Volokh Avatar answered Oct 22 '22 05:10

Danylo Volokh