[英]How to get height and width of a popup menu in android?
我有一个弹出菜单,我只想获取它的尺寸以在我的 showCaseView 中用于我的导览。 我在任何地方都找不到确定这些尺寸(高度和宽度)的方法。
private void initPopUpMenu() {
PopupMenu popupMenu = new PopupMenu(TimelineActivity.this, menuIcon);
popupMenu.getMenuInflater().inflate(R.menu.menu_timeline, popupMenu.getMenu());
}
如何从这个结构中检索宽度和高度? 这是一个简单的菜单资源,有 5 个项目
最好的解决方案是使用ListPopupWindow
而不是PopupMenu
,后者具有getWidth()
和getHeight()
方法来获取其尺寸。 但是,如果您真的想使用PopupMenu
,可能的棘手方法是使用Reflection
访问其内部ListView
,因为PopupMenu
没有可用的方法来访问内容视图。
用法:
PopupMenu popupMenu = initPopUpMenu();
popupMenu.show();
ListView listView = getPopupMenuListView(popupMenu);
androidx.core.view.ViewKt.doOnLayout(listView, view -> {
System.out.println("PopupMenu Size: " + view.getWidth() + " x " + view.getHeight());
return null;
});
方法:
private PopupMenu initPopUpMenu() {
PopupMenu popupMenu = new PopupMenu(TimelineActivity.this, menuIcon);
popupMenu.getMenuInflater().inflate(R.menu.menu_timeline, popupMenu.getMenu());
return popupMenu;
}
private ListView getPopupMenuListView(PopupMenu popupMenu) {
Method getMenuListViewMethod = null;
try {
getMenuListViewMethod = PopupMenu.class.getDeclaredMethod("getMenuListView");
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
ListView listView = null;
if (getMenuListViewMethod != null) {
getMenuListViewMethod.setAccessible(true);
try {
listView = (ListView) getMenuListViewMethod.invoke(popupMenu);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return listView;
}
构建.gradle:
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.3.0'
}
结果:
I/System.out:弹出菜单大小:539 x 660
您可以在PopupWindow
使用自定义布局,然后对其进行测量
val popupWindow = PopupWindow(context)
popupWindow.contentView = View.inflate(context, R.layout.my_popup, null).apply {
measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
)
measuredWidth// <-- here is width
measuredHeight// <-- here is height
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.