PopupWindow 適合做「浮動在當前畫面之上的小視窗」,例如按下按鈕後展開一組選項。它的使用有幾個不能漏掉的設定,以下用一個完整範例走過一次。
public class PopUpActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LayoutInflater inflater = LayoutInflater.from(this);
// 引入彈出視窗的版面配置
View view = inflater.inflate(R.layout.main2, null);
// 建立 PopupWindow 物件
final PopupWindow pop = new PopupWindow(view, LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, false);
Button btn = (Button) findViewById(R.id.btn);
// 必須設定背景,點擊外部才可消失
pop.setBackgroundDrawable(new BitmapDrawable());
// 設定點擊視窗外側即關閉
pop.setOutsideTouchable(true);
// 設定此參數才能獲得焦點,否則無法點擊
pop.setFocusable(true);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (pop.isShowing()) {
// 隱藏視窗;若已設定點擊外部消失,通常不需要這段
pop.dismiss();
} else {
// 顯示視窗
pop.showAsDropDown(v);
}
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dianji" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="AAAAA" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BBBBB" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CCCCC" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DDDDD" />
</LinearLayout>
三個最常被忽略的細節:setBackgroundDrawable 不設的話點外部不會消失(這也是舊版 Android 的已知地雷);setFocusable 不設的話視窗內的按鈕點不動;showAsDropDown 是相對於觸發它的 View 定位,若要置中或自訂位置則改用 showAtLocation。效果相當不錯,值得一試。