弹出窗口以显示片段中的某些内容

Sar*_*mer 21 android popup android-fragments

我试图制作类似弹出窗口的东西,当点击片段中的视图时会出现.我想要这个弹出窗口或其他什么,不要让片段变暗,就像Dialog Fragment那样.而且我还希望弹出窗口位于单击视图的位置.如果它有自己的活动和布局会很好,所以我可以做一些自定义的更改.你能告诉我一些示例代码吗?

Vik*_*ram 47

以下应符合您的规范完美.从内部调用此方法onClick(View v)OnClickListener分配给视图:

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());

}
Run Code Online (Sandbox Code Playgroud)

评论应该很好地解释这一点.anchorViewvonClick(View v).

  • 在片段中我必须使用`getActivity().getLayoutInflater()`. (2认同)