问题描述
我试图用ListPopupWindow通过显示字符串列表的 ArrayAdapter
(最终这将是一个更复杂的自定义适配器)。 code是如下。如截图所示,所产生的 ListPopupWindow
似乎充当如果内容宽度为零。它显示了项目的适当数量,项目仍然可点击,然后点击成功生产吐司
,所以至少这一点是正常工作。
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.
这是值得注意的一点是:我可以提供在像素宽度 popup.setWidth(...)
而不是 ListPopupWindow.WRAP_CONTENT
,它会显示一些内容,但这似乎非常不灵活。
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.
如何让我的 ListPopupWindow
包装其内容?
How do I make the ListPopupWindow
wrap its content?
测试活动:
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();
}
}
截图:
推荐答案
现在的问题是与 ListPopupWindow
的实施。我检查了源$ C $ C,并使用 setContentWidth(ListPopupWindow.WRAP_CONTENT)
或 setWidth(ListPopupWindow.WRAP_CONTENT)
使弹出的窗口中使用它的锚视图的宽度来代替。
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.
这篇关于ListPopupWindow不服从WRAP_CONTENT宽度规格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!