我正在尝试使用 ListPopupWindow 通过一个显示字符串列表ArrayAdapter
(最终这将是一个更复杂的自定义适配器)。代码如下。如屏幕截图所示,结果ListPopupWindow
似乎内容宽度为零。它显示了正确数量的项目,这些项目仍然是可点击的,并且点击成功会产生一个Toast
,所以至少有那么多工作正常。
一个有趣的注释:我可以提供一个以像素为单位的宽度来popup.setWidth(...)
代替ListPopupWindow.WRAP_CONTENT
它,它会显示一些内容,但这似乎非常不灵活。
如何使ListPopupWindow
包装的内容?
测试活动:
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();
}
}
截屏: