I am trying to make something like a pop-up window, that would appear when clicked on a view in a fragment. I want this pop-up window or whatever, to not make the fragment dark, like a Dialog Fragment does. And I also want the pop up to be positioned where the view is clicked. Would be good if it has its own activity and layout so I can do some custom changes in it. Can you plese show me some sample code?
Asked
Active
Viewed 3.9k times
1 Answers
51
The following should work perfect in accordance with your specification. Call this method from inside onClick(View v)
of OnClickListener
assigned to the View:
public void showPopup(View anchorView) {
View popupView = getLayoutInflater().inflate(R.layout.popup_layout, null);
PopupWindow popupWindow = new PopupWindow(popupView,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// Example: If you have a TextView inside `popup_layout.xml`
TextView tv = (TextView) popupView.findViewById(R.id.tv);
tv.setText(....);
// Initialize more widgets from `popup_layout.xml`
....
....
// If the PopupWindow should be focusable
popupWindow.setFocusable(true);
// If you need the PopupWindow to dismiss when when touched outside
popupWindow.setBackgroundDrawable(new ColorDrawable());
int location[] = new int[2];
// Get the View's(the one that was clicked in the Fragment) location
anchorView.getLocationOnScreen(location);
// Using location, the PopupWindow will be displayed right under anchorView
popupWindow.showAtLocation(anchorView, Gravity.NO_GRAVITY,
location[0], location[1] + anchorView.getHeight());
}
The comments should explain this well enough. anchorView
is the v
from onClick(View v)
.

Vikram
- 51,313
- 11
- 93
- 122
-
awesome, works so far, but how do I make it have a border or something? – Sartheris Stormhammer Aug 27 '13 at 10:28
-
1@БориславМинчев Well, place the whole `popup` layout inside a `FrameLayout` with black background. Set `popup` layout's background to white and give it a margin of `2dp`. – Vikram Aug 27 '13 at 21:12
-
too complicated :D I did it with a background picture with a frame, and the inside color transparent like 70%. anyway, the above answers was what I wanted thank you – Sartheris Stormhammer Aug 28 '13 at 07:12
-
2Inside a fragment I had to use `getActivity().getLayoutInflater()`. – Suragch Oct 28 '16 at 10:34