如何使用 Material Design Android 实现这个自定义弹出菜单? [英] How to realize this custom popup menu with Material Design Android?

查看:37
本文介绍了如何使用 Material Design Android 实现这个自定义弹出菜单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个像 ,但我找不到如何自定义此视图的布局.

解决方案

您可以使用 ListPopupWindow,提交您的自定义适配器,通过它您可以控制ListPopupWindow 的每一行的布局.对于普通的 PopupWindow,你必须提供一个锚视图,另外你必须在 ListPopupWindow 的实例上调用 setContentWidth,它设置宽度弹出窗口的内容大小.这是你必须付出的一个小代价,但对于一个小数据集来说并不是什么大问题.我有这个实用方法来检索行的最大宽度:

public int measureContentWidth(ListAdapter adapter) {int maxWidth = 0;int count = adapter.getCount();最终 int widthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);最终 int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);查看 itemView = null;for (int i = 0; i < count; i++) {itemView = adapter.getView(i, itemView, this);itemView.measure(widthMeasureSpec, heightMeasureSpec);maxWidth = Math.max(maxWidth, itemView.getMeasuredWidth());}返回最大宽度;}

I want to realize a custom popup menu like Twitter in Android for example with item and picture but I don't know what's the component used for that.

In Material Design website, google present this solution. So I think, there is a native solution to achieve this.

I tried with Popup menu, but I can't find how to customize the layout of this view like that.

解决方案

you can use a ListPopupWindow, submitting your custom adapter, through which you can control the layout of every single row of the ListPopupWindow. As for a normal PopupWindow you have to provide an anchor view and additionally you have to call setContentWidth on the instance of ListPopupWindow, which sets the width of the popup window by the size of its content. It is a small price you have to pay, but for a small dataset is not a big deal. I have this utility method to retrieve the max width of the row:

public int measureContentWidth(ListAdapter adapter) {
    int maxWidth = 0;
    int count = adapter.getCount();
    final int widthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
    final int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
    View itemView = null;
    for (int i = 0; i < count; i++) {
        itemView = adapter.getView(i, itemView, this);
        itemView.measure(widthMeasureSpec, heightMeasureSpec);
        maxWidth = Math.max(maxWidth, itemView.getMeasuredWidth());
    }
    return maxWidth;
}

这篇关于如何使用 Material Design Android 实现这个自定义弹出菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆