android-显示来自片段的弹出窗口
作者:互联网
当单击按钮时,我想显示来自我的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;
}
}
解决方法:
popwindow在片段和活动中几乎相同,除了它们使您获得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);
标签:android-fragments,placeholder,android-view,android-popupwindow,android 来源: https://codeday.me/bug/20191121/2055417.html