Android弹出窗口不能填满屏幕大小?
Android弹出窗口不能填满屏幕大小?
我试图制作一个简单的弹出窗口。但是每次我制作一个,它都会变得非常小...而且不是我想要的长度。弹出窗口的样子如下:
[图片链接](https://i.stack.imgur.com/ijdKCl.png)
这是弹出窗口的布局:
这是我的Java代码:
private PopupWindow pw; private void bindActivity() { fabButton = (ImageButton) findViewById(R.id.activity_profileView_FAB); fabButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { initiatePopupWindow(); } }); } private void initiatePopupWindow() { try { //我们需要获取LayoutInflater的实例,使用此活动的上下文 LayoutInflater inflater = (LayoutInflater) ProfileView.this .getSystemService(Context.LAYOUT_INFLATER_SERVICE); //从预定义的XML布局中填充视图 View layout = inflater.inflate(R.layout.popup, (ViewGroup) findViewById(R.id.popup_element)); //创建一个宽度为300px,高度为470px的PopupWindow pw = new PopupWindow(layout, 300, 470, true); //在中心显示弹出窗口 pw.showAtLocation(layout, Gravity.CENTER, 0, 0); TextView mResultText = (TextView) layout.findViewById(R.id.server_status_text); Button cancelButton = (Button) layout.findViewById(R.id.end_data_send_button); cancelButton.setOnClickListener(cancel_button_click_listener); } catch (Exception e) { e.printStackTrace(); } } private View.OnClickListener cancel_button_click_listener = new View.OnClickListener() { public void onClick(View v) { pw.dismiss(); } };
无法弄清楚为什么它不起作用...
我该如何获得我想要的尺寸?
PopupWindow在Android中经常用于显示类似对话框的弹出窗口。然而,有时候我们会遇到一个问题,即PopupWindow弹出后无法填充整个屏幕。本文将介绍造成这个问题的原因以及解决方法。
问题的原因是在创建PopupWindow时指定了固定的宽度和高度,而没有使用MATCH_PARENT来自适应屏幕大小。解决方法是将代码中的宽度和高度参数修改为MATCH_PARENT,如下所示:
pw = new PopupWindow(layout, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
此外,如果需要在任一侧添加边距,可以在PopupWindow的布局文件中进行设置。同时,在布局文件中使用android:layout_height="wrap_content"可以确保在任何设备屏幕上都能显示相同的样式(如果添加了边距)。
通过以上修改,PopupWindow将会自适应屏幕大小,并且在任何设备上都能以相同的样式显示。这样就解决了Android中PopupWindow不填充整个屏幕的问题。
这个问题的出现原因是在弹出窗口(popup window)中无法使用popup window xml中的布局。解决方法是使用主布局中的任何一个视图作为弹出窗口的视图。目前,作者使用FloatingButton作为视图来显示弹出窗口。
fabButton = (ImageButton) findViewById(R.id.activity_profileView_FAB); fabButton.setOnClickListener(new View.OnClickListener() { public void onClick(final View v) { initiatePopupWindow(v); } }); private void initiatePopupWindow(View v) { try { LayoutInflater inflater = (LayoutInflater) ProfileView.this .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.popup, (ViewGroup) findViewById(R.id.popup_element)); pw = new PopupWindow(layout, 300, 470, true); pw.showAtLocation(v, Gravity.CENTER, 0, 0); TextView mResultText = (TextView) layout.findViewById(R.id.server_status_text); Button cancelButton = (Button) layout.findViewById(R.id.end_data_send_button); cancelButton.setOnClickListener(cancel_button_click_listener); } catch (Exception e) { e.printStackTrace(); } }
以上代码中,通过点击FloatingButton来调用initiatePopupWindow方法,该方法中使用LayoutInflater来加载popup.xml布局文件,并将其作为视图传递给PopupWindow的构造函数。最后,通过showAtLocation方法将弹出窗口显示在中心位置。布局中的TextView和Button都可以通过findViewById来获取并进行操作。