Pop up window to display some stuff in a fragment

38,156

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).

Share:
38,156
Sartheris Stormhammer
Author by

Sartheris Stormhammer

Updated on October 06, 2022

Comments

  • Sartheris Stormhammer
    Sartheris Stormhammer over 1 year

    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?

  • Sartheris Stormhammer
    Sartheris Stormhammer over 10 years
    awesome, works so far, but how do I make it have a border or something?
  • Vikram
    Vikram over 10 years
    @БориславМинчев 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.
  • Sartheris Stormhammer
    Sartheris Stormhammer over 10 years
    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
  • Suragch
    Suragch over 7 years
    Inside a fragment I had to use getActivity().getLayoutInflater().