我想为 ListView 的每个列表项添加三点菜单。

**这是我的 ListView 适配器 getView 方法 **

 @Override
public View getView(final int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = activity.getLayoutInflater();
    View inflate = inflater.inflate(R.layout.book_item_new, null, false);
    findViews(inflate);

    bookTitle.setText(books.get(position).getName());
    bookPrice.setText(books.get(position).getPrice() + " ₹");
    semBranch.setText(books.get(position).getSemester() + " Sem " + books.get(position).getBranch());
    date.setText(books.get(position).getpDate());
    senderName.setText(books.get(position).getSender());

    return inflate;
}

最佳答案

ImageView 布局中添加带有三点图像的 book_item_new

<ImageView
    android:id="@+id/imbPopUp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentEnd="true"
    android:layout_centerVertical="true"
    android:paddingLeft="18dp"
    android:paddingRight="18dp"
    android:src="@drawable/icon_menu_dot" />

并在您的 OnclickListener 中的此 imageview 上设置 getView(),如下所示。
imageView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                showPopupMenu(imageView, position);
            }
        });


    /**
     * Showing popup menu when tapping on 3 dots
     */
    private void showPopupMenu(View view, int position) {
        PopupMenu popup = new PopupMenu(context, view, Gravity.END);
        MenuInflater inflater = popup.getMenuInflater();

        inflater.inflate(R.menu.favourite_menu, popup.getMenu());

        //set menu item click listener here
        popup.setOnMenuItemClickListener(new MyMenuItemClickListener(position));
        popup.show();
    }

现在为您的菜单项单击创建单击监听器类,如下所示。
/**
     * Click listener for popup menu items
     */
    class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener {
        int position;

        /**
         * @param position
         */
        MyMenuItemClickListener(int position) {

            this.position = position;
        }

        /**
         * Click listener for popup menu items
         */

        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.view:
                   // ...
                    return true;
                case R.id.edit:
                    // ...
                    return true;
                case R.id.delete:
                    // ...
                    return true;
                case R.id.favourite:
                   // ...
                    return true;
                default:
            }
            return false;
        }
    }

关于java - 如何在 ListView 中为每个列表项添加三点菜单?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58229791/

10-11 14:23