Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

使用 PopupWindow 模擬標題選項卡的 Android 做法

編輯:關於 Android 程式設計

使用 PopupWindow 模擬標題選項卡

在 Android 中,標題列的選項卡可使用 Dialog 或 PopupWindow 實作。相較於自訂 Dialog,PopupWindow 更輕量,適合顯示短暫選單或下拉式選項。

建立 PopupWindow

先將清單布局 inflate 出來,再設定 PopupWindow 的寬高、焦點與外部觸控行為:

popupWindow = new PopupWindow(MainActivity.this);
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.setWidth(getWindowManager().getDefaultDisplay().getWidth() / 2);
popupWindow.setHeight(300);
popupWindow.setOutsideTouchable(true);
popupWindow.setFocusable(true);
popupWindow.setContentView(layout);

顯示位置

可使用 showAtLocation 指定位置,並搭配 Gravity 控制對齊:

popupWindow.showAtLocation(findViewById(R.id.main),
        Gravity.LEFT | Gravity.TOP, x, y);

若使用 showAsDropDown,則會以指定 View 作為參照,適合做為標題按鈕的下拉選單。

點擊回傳

為 ListView 設定 OnItemClickListener,在使用者選擇項目後更新標題文字並關閉 PopupWindow:

listView.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView parent, View view, int position, long id) {
        button.setText(title[position]);
        popupWindow.dismiss();
        popupWindow = null;
    }
});

實作時需特別注意 y 座標計算,若位置落在按鈕中央,可檢查 getBottom 與螢幕座標換算是否正確。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved