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

Android PopupWindow 基礎用法完整示範

編輯:關於 Android 程式設計

PopupWindow 適合實作「浮動在當前畫面之上」的輕量互動元件,例如點一下按鈕展開的下拉選單。以下用一個最典型的例子走過整個流程:點擊按鈕後,在其下方彈出一個分類清單,選項被選中後回填到按鈕文字上。

一、Activity 程式碼

public class MainActivity extends AppCompatActivity {

    private Button button;
    private PopupWindow kindsPopupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                getKindPopupWindow();
            }
        });
    }

    private void getKindPopupWindow() {
        final ArrayList<String> kindsList = new ArrayList<>();
        kindsList.add("全部分類");
        kindsList.add("今日上線");
        kindsList.add("美食");
        kindsList.add("酒店");
        kindsList.add("旅遊");

        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.pop_local_kind, null);

        kindsPopupWindow = new PopupWindow(view,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, false);

        // 讓寬度對齊按鈕
        kindsPopupWindow.setWidth(button.getWidth());

        ListView listView = (ListView) view.findViewById(R.id.list);
        listView.setAdapter(new PopAdapter(MainActivity.this, kindsList));

        // 必須設定背景,否則點擊外部不會消失
        kindsPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        kindsPopupWindow.setOutsideTouchable(true);
        // 必須可取得焦點,否則列表項無法點擊
        kindsPopupWindow.setFocusable(true);
        // 顯示在按鈕下方
        kindsPopupWindow.showAsDropDown(button);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
                Toast.makeText(MainActivity.this, i + "pop", Toast.LENGTH_SHORT).show();
                button.setText(kindsList.get(i));
                kindsPopupWindow.dismiss();
            }
        });
    }

    private class PopAdapter extends BaseAdapter {
        private Context context;
        private ArrayList<String> list;

        public PopAdapter(Context context, ArrayList<String> list) {
            this.context = context;
            this.list = list;
        }

        @Override public int getCount() {
            return (list == null || list.isEmpty()) ? 0 : list.size();
        }
        @Override public Object getItem(int i) { return list.get(i); }
        @Override public long getItemId(int i) { return i; }

        @Override
        public View getView(int i, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(context)
                        .inflate(R.layout.item_pop_local_kind, null);
                holder.textView = (TextView) convertView.findViewById(R.id.item_text);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.textView.setText(list.get(i));
            return convertView;
        }

        private class ViewHolder {
            TextView textView;
        }
    }
}

二、首頁布局

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show PopupWindow" />
</LinearLayout>

三、PopupWindow 布局

這裡放一個 ListView,實務上可依需求換成任何版面:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#ffffff">

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#888888" />
</LinearLayout>

四、清單項布局

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/white">

    <TextView
        android:id="@+id/item_text"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:gravity="center"
        android:text="pop"
        android:textColor="#f08e1f"
        android:background="#eeeeee" />
</LinearLayout>

五、三個容易踩到的雷

初學 PopupWindow 時最常遇到的三個問題,其實都有明確原因:

  • 點擊外部不會消失——因為沒有設定背景 Drawable。呼叫 setBackgroundDrawable(new BitmapDrawable()) 之後,setOutsideTouchable(true) 才會生效。
  • 列表項點不動——PopupWindow 預設不搶焦點,必須 setFocusable(true) 才能正常接收觸控事件。
  • 位置跑掉——showAsDropDown() 是相對於目標 View 定位;若希望自訂座標,可改用 showAtLocation()。另外別忘了在 Activity 銷毀時呼叫 dismiss(),避免視窗洩漏。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved