【问题标题】:Showing a popup window from Fragment从 Fragment 显示弹出窗口
【发布时间】:2014-05-11 10:41:37
【问题描述】:

我想在单击按钮时从我的 PlaceHodler 类中显示一个扩展 Fragment 的弹出窗口。为了测试,我编写了这段代码,它确实有效,但我想这很荒谬(使用 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;
    }
}

【问题讨论】:

  • 需要注意的一点是,您的按钮不必是最终的。您可以只使用“视图”,因为它被传递到您的 onClick() 方法中。也就是说,您也可以使用任何可以分配 OnClickListener 的东西来完成这项工作。作为实验,我将您的代码与 TextView 一起使用。完美的工作,但是,关闭窗口的想法?

标签: android android-fragments android-view placeholder android-popupwindow


【解决方案1】:

片段和活动中的弹出窗口几乎相同,除了它们获得 contrext 的方式,在活动 this 中,片段 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-14
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    相关资源
    最近更新 更多