Search code examples
javadynamicandroid-listviewpositionpopupwindow

Android ListView onItemClick show Popup on exact position


I have a PopupWindow which is shown as a drop down when I click a Item on my ListView:

@Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            View v = getLayoutInflater().inflate(R.layout.popup_click_menu, null);
            final PopupWindow mypopupWindow = new PopupWindow(v,300, RelativeLayout.LayoutParams.WRAP_CONTENT, true);
            mypopupWindow.showAsDropDown(view, -153, 0);
        }

The result is this:

ListView with two Items, the last one is clicked

My question is: I want to have a dynamic position of my pop up. So if I click on the middle of the Item then it should be shown in the middle. How can I do that?


Solution

  • You can solve this with a TouchListener:

    list.setOnTouchListener(new OnTouchListener() {
                public boolean onTouch(View view, MotionEvent event) {
                    positionX = (int) event.getX();
    
                    return false; // not consumed; forward to onClick
                }
            });
    

    Then you have the exact x-position and you can move the PopupWindow by onItemClick:

    mypopupWindow.showAsDropDown(view, positionX, 0);