彈窗佈局:java
<?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="#000" android:orientation="vertical"> <Button android:id="@+id/btn_popup_windows_item1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp" android:text="Item1" android:textSize="18sp"/> <Button android:id="@+id/btn_popup_windows_item2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp" android:text="Item2" android:textSize="18sp"/> </LinearLayout>
void showPopupWindow(View view){ View viewpw =View.inflate(TestActivity.this,R.layout.item_popup_window_layout,null); Button btn1=(Button) viewpw.findViewById(R.id.btn_popup_windows_item1); //設置背景透明效果 (注意Background必須背景色)(範圍0~255) viewpw.getBackground().setAlpha(100); //建立PopupWindow 並設置寬 高 final PopupWindow popupWindow = new PopupWindow(viewpw, ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); //設置焦點,這樣的或就能夠實現點擊popupWindow外部區域,關閉popupWindow popupWindow.setFocusable(true); //設置顯示位置 popupWindow.showAsDropDown(view, 60,0); //指定View的下方 //popupWindow.showAtLocation(view, Gravity.CENTER,0,0); //屏幕中心 btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(TestActivity.this, "You click Item1", Toast.LENGTH_SHORT).show(); popupWindow.dismiss(); //關閉 PopupWindow } }); }