直接看代码:
public class ThirdActivity extends Activity{ private Button but , but1 ; private AlertDialog dialog ; private AlertDialog.Builder builder; private ProgressDialog progressDialog ; private SexDialog dialogBottom ; private PopupWindow popupWindow ; private View popupWindowView ; private WindowManager.LayoutParams lp ; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView( R.layout.thirdlayout); but = (Button) findViewById( R.id.but3); but1 = (Button) findViewById( R.id.but33); initPopupWindow(); but1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (popupWindow.isShowing()){ popupWindow.dismiss(); }else{ backgroundAlpha(ThirdActivity.this , 0.5f); popupWindow.showAsDropDown(v); } } }); } /** * popudWindow初始化 */ private void initPopupWindow(){ popupWindowView = LayoutInflater.from(this).inflate(R.layout.popmenu_add2, null); popupWindow = new PopupWindow(popupWindowView, ViewPager.LayoutParams.WRAP_CONTENT, ViewPager.LayoutParams.WRAP_CONTENT); //设置点击窗口外边窗口消失 popupWindow.setBackgroundDrawable(new BitmapDrawable()); popupWindow.setOutsideTouchable(true); // 设置此参数获得焦点,否则无法点击 popupWindow.setFocusable(true); popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { backgroundAlpha(ThirdActivity.this , 1f); } }); } /** * 设置popupwindow背景显示变暗 */ public void backgroundAlpha(Activity activity, float bgAlpha) { lp = this.getWindow().getAttributes(); lp.alpha = bgAlpha; activity.getWindow().setAttributes(lp); } }
popmenu_add2.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" android:orientation="vertical" android:padding="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableLeft="@drawable/menu_scan" android:drawablePadding="10dp" android:text="扫一扫" android:textColor="#ff333333" android:textSize="16sp"/> </LinearLayout>
使用popupWindow是需要注意的几个问题
1 . 由于popupWindow没有继承ViewGroup类,所以inflatter.inflater()的第二个参数只能传null,传null时会使最外层的布局android:layout_XXX都不起作用。所以高度一第二个布局为主。
2 . 为了设置背景和边距,其背景只能设置在第二层布局里,由于第一层布局的android:layout_xxx都不起作用,而设置android:apping_xxx也不影响背景。
3 . 为了点击popupWindow的外面能消失,几个属性需要一起设置破噗噗Window.setOutsideTouchable(true) ;popupWindow.setBackgroundDrawable()