简体   繁体   中英

How to PopupMenu at ListView row?

First, the code...

ListView listView = (ListView) findItemById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(){
    public void onClick(final int position, final View convertView, final ViewGroup parent){
        PopupMenu popupMenu = new PopupMenu(MainActivity.this, adapter.getView(position, convertView, parent));
        popupMenu.inflate(R.menu.menu);
    }
};
listView.setAdapter(adapter);

But the menu pops up at the top left of the screen, not at the row. What must I do to achieve that?

You would need to get the rows position, grab its top and bottom positions and inflate the popup with those numbers, you have to do it on the listview level and call it from the adapter or handle it all on the listview level.

This is one way of doing it:

 lvList = (ListView) findViewById(R.id.lvList);
    lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.d(TAG, "Top of view =" + view.getTop());
            Log.d(TAG, "Bottom of view = " + view.getBottom());
        }
    });

I am grabbing the info parameters there, in the onItemCLick , but you can do it anywhere and you probably could do it in the Adapter, I am use to doing it for animation and I do it on the ListView level.

Just make a fragment. Sample code is called "Action Bar Compat - List Popup Menu".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM