How to get the position of an Item from a PopupMenu in a custom ListView

爱⌒轻易说出口 提交于 2019-12-05 23:56:16

问题


Here's the problem: I've got a custom ArrayAdapter (overriden getView). Each item has got

  • 2 ImageView
  • 2 EditText

One of those ImageView is clickable and enables a PopupMenu, so I've got a little PopupMenu for each item of the list. Now, for that menu I need some parameters from the item to wich is anchored. So, how to pass informations (like position) to the method called from the PopupMenu voice? Attached the xml files.

item_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:paddingBottom="5dp"
    android:paddingTop="5dp" >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginRight="6dip"
        android:contentDescription="TODO"
        android:src="@drawable/ic_launcher" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/firstLine"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:maxHeight="60dp"
            android:text="Title"
            android:textSize="16sp" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:contentDescription="TODO"
            android:onClick="showMenu"
            android:src="@drawable/abc_ic_menu_moreoverflow_normal_holo_light" />

        <TextView
            android:id="@+id/secondLine"
            android:layout_width="fill_parent"
            android:layout_height="26dip"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/firstLine"
            android:ellipsize="marquee"
            android:singleLine="true"
            android:text="Author"
            android:textSize="12sp" />

    </RelativeLayout>

</LinearLayout>

menu_item.xml

<?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android" >

        <item
            android:id="@+id/preview"
            android:onClick="preview"
            android:title="@string/preview"/>
        <item
            android:id="@+id/download"
            android:onClick="download"
            android:title="@string/download"/>

    </menu>

CustomArrayAdapter.java

public class CustomArrayAdapter extends ArrayAdapter<Custom>{

    private final Context context;
    private final List<Custom> values;
    private final int resource;
    private final ImageCache imgCache = new ImageCache();

    public CustomArrayAdapter(Context context, int resource, List<Custom> values) {
        super(context, resource, values);
        this.context = context;
        this.values = values;
        this.resource = resource;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder vh;
        Custom Custom = values.get(position);
        if (convertView == null) {
            vh = new ViewHolder();
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(resource, parent, false);
            vh.title = (TextView) convertView.findViewById(R.id.firstLine);
            vh.author = (TextView) convertView.findViewById(R.id.secondLine);
            vh.albumImage = (ImageView) convertView.findViewById(R.id.icon);
            convertView.setTag(vh);
        }
        else {
            vh = (ViewHolder)convertView.getTag();
        }
        vh.requestedCustom = Custom;
        vh.title.setText(Custom.getTitle());
        vh.author.setText(Custom.getAuthor());
        String imgUrl = Custom.getImgUrl();
        if (imgUrl != null) {
            imgCache.getImage(Custom, vh);
        }
        else {
            vh.albumImage.setImageResource(R.drawable.no_album);
        }
        return convertView;
    }

    // This is a ViewHolder that helps in the view recycling
    public static class ViewHolder {
        public Custom requestedCustom;
        public TextView title;
        public TextView author;
        public ImageView albumImage;
    }
}

"preview" and "download" methods need parameters from the associated list item and I don't know how to get them. Thanks again.

EDIT 1

It seems that a Contextual Menu should be used instead (right?) but I would like to anchor it to each item as a sort of popup menu that appears. So how can I achieve this? For those who don't understand what I want (due to my worst english): Google Play app, popup menu that let you choose between "Install" or "Add to whishlist".


回答1:


You can create your listener class like this:

class myClickListener implements OnClickListener, OnMenuItemClickListener {

        long id;

        public myClickListener(long id) {
            this.id = id;
        }
        @Override
        public void onClick(View v) {
            PopupMenu popup = new PopupMenu(appContext, v);
            popup.setOnMenuItemClickListener(this);
            MenuInflater inflater = popup.getMenuInflater();
            inflater.inflate(R.menu.menu_item, popup.getMenu());
            popup.show();
        }
        @Override
        public boolean onMenuItemClick(MenuItem arg0) {
            Toast.makeText(appContext, "ID of selected row : " + id , Toast.LENGTH_SHORT).show();
            return false;
        }

    }

and add this listener to your imageview at your override getView method of adapter class:

imageView.setOnClickListener(new myClickListener(getItemId(position)));



回答2:


Simply we need to set buttons tag as its position, and onClick on the PopupButton you need to get the view:

button.setTag(position);  //may be you can call this on getview method of list view
button.setOnClickListener(new View.OnClickListener() { 
    public void onClick(View v) {
        int position = (Integer) v.getTag();   // you will get the position

    }
});

or use Interface in your fragment implements View.OnClickListener

private void showPopupMenu(View view) {

    final   int position = (Integer) view.getTag();

        PopupMenu popup = new PopupMenu(getActivity(), view);

        // Inflate our menu resource into the PopupMenu's Menu
        popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());

        // Set a listener so we are notified if a menu item is clicked
        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                case R.id.menu_remove:


                System.out.println(position);
                    return true;
                }
                return false;
            }
        });

        // Finally show the PopupMenu
        popup.show();
    }



回答3:


There is no way to achieve what you want with a onClick declared by XML. The easiest way to solve it with your actual implementation is to :

  • add a real click listener to your ImageView after inflating it. Inside your adapter.
  • the listener should be a custom class implementing the OnClickListener interface
  • you should also give your listener an additional data member : the position (row) that contains the ImageView.
  • when the listener is activated, it will have to invoke a callback on the activity that will display the Dialog, the listener will then pass the position.



回答4:


Here's how I did it:

  1. Instead of storing a ViewHolder in the tags of convertView in CustomArrayAdapter's getView(int position, View convertView, ViewGroup parent) method, I stored the Custom object itself. I didn't even use a holder.

    convertView.setTag(getItem(position));
    

    (if you really need to store the ViewHolder, you can use setTag(int key, Object tag) to store multiple tags)

  2. When showMenu(View view) is called by the ImageView, I use view.getParent() to get the parent LinearLayout of the currently selected view, which has my Custom object in its tag.

    View parent = (View) view.getParent();
    
  3. Outside showMenu() I have defined a public property to store the currently selected item like this:

    public static Custom mSelectedItem;
    
  4. Inside showMenu() I set mSelectedItem to getTag() of the parent LinearLayout from step 2.

    mSelectedItem = (Custom) parent.getTag();
    
  5. Finally, in the onMenuItemClick(MenuItem menuItem) override method I use mSelectedItem to determine the currently selected item.

    Custom custom = mSelectedItem;
    


来源:https://stackoverflow.com/questions/20002051/how-to-get-the-position-of-an-item-from-a-popupmenu-in-a-custom-listview

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