从Fragment中显示弹出窗口

5
当按钮被点击后,我希望从扩展Fragment的PlaceHolder类中显示一个弹出窗口。为了测试,我编写了这段代码,它真的可以工作,但我认为它很荒谬(使用Button对象作为父视图等...我找不到另一种方法使其正常工作...)。请查看这段代码,并建议我如何改进它。请不要因为我是一个非常初学者的程序员而评判我。
我的代码:
public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        final Button button1 = (Button)rootView.findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i("ilog", "onClick() works");
                PopupWindow pw = new PopupWindow(getActivity());
                TextView tv = new TextView(getActivity());
                LayoutParams linearparams1 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                tv.setLayoutParams(linearparams1);
                tv.setText("Testing");
                pw.setContentView(tv);
                pw.setWidth(400);
                pw.setHeight(180);
                pw.showAtLocation(button1, Gravity.CENTER_HORIZONTAL, 25, 25);
                pw.update();
            }
        });
        return rootView;
    }
}

需要注意的一点是,您的按钮不必是最终版本。您可以只使用“view”,因为它被传递到了您的onClick()方法中。也就是说,您可以将任何可以分配OnClickListener的内容与此配合使用。作为一个实验,我使用了您的代码和一个TextView。完美地工作,但是对于关闭窗口有什么想法吗? - Bill Mote
1个回答

6

在 Fragment 和 Activity 中,除了获取上下文的方式不同外,popwindow 的创建方法几乎相同。在 Activity 中使用 this 获取上下文,在 Fragment 中使用 getActivity()。

以下是创建 popwindow 的代码:

    View popupView = LayoutInflater.from(getActivity()).inflate(R.layout.popup_layout, null);
    final PopupWindow popupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);

// define your view here that found in popup_layout 
// for example let consider you have a button 

Button btn = (Button) popupView.findViewById(R.id.button);

// finally show up your popwindow
popupWindow.showAsDropDown(popupView, 0, 0);

参考 PopupWindow


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接