I have an onClickListener on a button inside my listView elements, which needs to show a popup under itsself.
The way I tried to achieve it was to simply use v.getBottom()
inside the onClickListener. However this would not return the correct position of the clicked button.
I then tried to get the position by calculating the yPosition of the listItem using this answer to get the exact scroll position: https://stackoverflow.com/a/10808454/3963566
View c = listView.getChildAt(0);
int yPosition = (int) listView.getChildAt(position).getBottom() - (-c.getTop() + listView.getFirstVisiblePosition() * c.getHeight());
popupWindow.showAtLocation(listView, Gravity.CENTER, 0, yPosition);
Adapter Code:
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.search_result, parent, false);
listView = (ListView) parent;
mainContainer = (LinearLayout) parent.getParent().getParent().getParent();
ibEmployment = (SquareImageButton) rowView.findViewById(R.id.ib_employment);
ibEmployment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showEmploymentPopup(v, position);
}
});
}
private void showEmploymentPopup(View v, int position) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.popup_categories,null);
PopupWindow pw = new PopupWindow(layout, 400, 600, true);
// display the popup in the center
pw.showAtLocation(v, Gravity.TOP, 0, v.getTop() + v.getMeasuredHeight() + 300);
initializeCategoriesList(position);
setCertificateStatus(position);
pw.showAsDropDown(v);
}
But the yPosition is only accurate for the first two list items as long as the list was not scrolled.