How to add overflow icon items in a card in Android

青春壹個敷衍的年華 提交于 2019-12-05 04:49:09
Gabriele Mariotti

First of all you shouldn't use this lib only to achieve an overflow menu inside a card.

Said that,the CardView in support Library is a FrameLayout with any model behind. The best way to achieve it, now is to use the new Toolbar inside the CardView layout.

Also you can add a ImageView inside the CardView layout and do something like this:

PopupMenu popup = new PopupMenu(getContext(), mImageButton);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.your_menu, popup.getMenu());

Finally (but it is not so important) if it isn't enough, the new cardslib (coming soon) will use the CardView in support library.

Here's how to do it correctly in an android.support.v7.widget.CardView. In my example, it's a cardview inside of a RecyclerView, so I set this up in the adapter, inside the onBindViewHolder method:

public class DashboardItemAdapter extends RecyclerView.Adapter<DashboardItemAdapter.ViewHolder> {
    ArrayList<Item> mItems = new ArrayList<>();
    private Context mContext;

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        mContext = parent.getContext();
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_dashboard, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder vh, int position) {
        final Item item = mItems.get(position);

        ...

        PopupMenu popup = new PopupMenu(mContext, vh.btnMenu);
        popup.inflate(R.menu.dashboard_card_waiting);
        popup.setOnMenuItemClickListener(item -> {
            switch (item.getItemId()) {
                case R.id.action_cancel:
                    cancelItem();
                    return true;
                default:
                    return true;
            }
        });
        vh.btnMenu.setOnClickListener(btn -> popup.show());
    }

    ...
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!