androiduser-interfacepopupwindow

ListPopupWindow not obeying WRAP_CONTENT width spec


I'm trying to use ListPopupWindow to show a list of strings via an ArrayAdapter (eventually this will be a more complex custom adapter). Code is below. As shown in the screenshot, the resulting ListPopupWindow seems to act as if the content width is zero. It shows the proper number of items, the items are still clickable, and clicking successfully produce a Toast, so at least that much is working properly.

An interesting note: I could supply a width in pixels to popup.setWidth(...) instead of ListPopupWindow.WRAP_CONTENT and it will show some of the content, but this seems very inflexible.

How do I make the ListPopupWindow wrap its content?

Test activity:

public class MainActivity extends Activity {

    private static final String[] STRINGS = {"Option1","Option2","Option3","Option4"};
    private View anchorView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActionBar().setHomeButtonEnabled(true);
        setContentView(R.layout.activity_main);
        anchorView = findViewById(android.R.id.home);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                showPopup();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showPopup() {
        ListPopupWindow popup = new ListPopupWindow(this);
        popup.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, STRINGS));
        popup.setAnchorView(anchorView);
        popup.setWidth(ListPopupWindow.WRAP_CONTENT);
        popup.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, "Clicked item " + position, Toast.LENGTH_SHORT).show();
            }
        });
        popup.show();
    }
}

screenshot:

enter image description here


Solution

  • The problem is with the implementation of ListPopupWindow. I checked the source code, and using setContentWidth(ListPopupWindow.WRAP_CONTENT) or setWidth(ListPopupWindow.WRAP_CONTENT) makes the popup window use the width of its anchor view instead.