如何在android中获得弹出菜单的高度和宽度?

y1aodyip  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(622)

我有一个弹出式菜单,我只想得到它的尺寸在我的展示视图中使用我的导游。我在任何地方都找不到确定这些尺寸(高度和宽度)的方法。

private void initPopUpMenu() {
    PopupMenu popupMenu = new PopupMenu(TimelineActivity.this, menuIcon);
    popupMenu.getMenuInflater().inflate(R.menu.menu_timeline, popupMenu.getMenu());
}

如何从这个结构中检索宽度和高度?这是一个包含5个项目的简单菜单资源

jljoyd4f

jljoyd4f1#

最好的解决办法是使用 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

zqdjd7g9

zqdjd7g92#

可以将自定义布局用于 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
}

相关问题