How to create a Spinner widget inside of a PopupWi

2019-06-03 05:00发布

问题:

I've been searching the web for the solution to this problem, but, unfortunately, I can't seem to find the answer. I created an XML file for a PopupWindow with a Spinner inside of it. Inside a button event listener, I call the following code to inflate the PopupWindow and display it on the screen.

LayoutInflater inflater = getLayoutInflater();
settings_layout = inflater.inflate(R.layout.setting_popout, (ViewGroup) findViewById(R.id.setting_popout));

// Creates a popup window of required width and height, and displays
// the popup in the center of the screen.
pw_settings = new PopupWindow(settings_layout, 400, 470, true); 
pw_settings.showAtLocation(settings_layout, Gravity.CENTER, 0, 0);

spColors = (Spinner) settings_layout.findViewById(R.id.linecolor);

// Sets the initial values of the color spinner and the listener
ArrayAdapter<CharSequence> adapter_color = 
    ArrayAdapter.createFromResource(this, R.array.colors_array, android.R.layout.simple_spinner_item);
adapter_color.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spColors.setAdapter(adapter_color);
spColors.setSelection(adapter_color.getPosition(over.color));

When clicking the button, the popup window shows up fine. However, I get the following error in LogCat when I click on the Spinner.

android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W@41402a90 is not valid; is your activity running? ...

I'm not sure what I'm doing wrong. Any help would be greatly appreciated! Thank you!

回答1:

It may be a bit late, and not exactly an answer to the original question, but I found from another question here that inserting the following line into the xml for my spinner prevented that error from occurring.

android:spinnerMode="dialog"



回答2:

I have run in to this problem a couple of times now, and the only non time consuming method I have found is the one proposed by Mike Fosker above.

android:spinnerMode="dialog"

makes the options list for the spinner show up in a separate pop-up, which does not trip the initial pop-up window you opened in your code. For example :

<Spinner
android:id="@+id/myspinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:spinnerMode="dialog" />


回答3:

Try:

settings_layout = inflater.inflate(R.layout.setting_popout, null);
((ViewGroup) findViewById(R.id.setting_popout)).addView(settings_layout);

Also, why are you attaching the layout in your popup to a ViewGroup already inside your activity? Chances are you can just get away with:

settings_layout = inflater.inflate(R.layout.setting_popout, null);