Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 用 PopupWindow 實作彈出式選單

以下步驟示範如何用 PopupWindow 做出一個四列的圖示選單。

step1:新建專案 PopWindow,並把選單要用的圖片匯入 /res/drawable 目錄。

(專案總覽圖)(drawable 目錄截圖)

step2:設定 UI 版面

a. 應用的整體版面,main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/main"
    >
    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/button"
        android:onClick="openPopWindow"
        />
</LinearLayout>

b. 彈出選單的版面,popwindow.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:background="@drawable/rectangle">  <!-- 手繪的長方形背景 -->
    <GridView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:numColumns="4"
        android:horizontalSpacing="10dp" android:verticalSpacing="10dp"
        android:id="@+id/gridView" />
</LinearLayout>

其中 android:background="@drawable/rectangle" 引用的是 rectangle.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient android:startColor="#1DC9CD" android:endColor="#A2E0FB"
        android:angle="270" />
    <padding android:left="2dp" android:top="2dp" android:right="2dp"
        android:bottom="2dp" />
</shape>

設計說明:主版面只放一顆按鈕,透過 android:onClick="openPopWindow" 觸發;彈出層用 GridView 排四列圖示,背景則是 shape 定義的 270 度漸層,加上 2dp 內距讓邊緣不生硬。在 Activity 中 new 一個 PopupWindow,把 popwindow 版面 inflate 進去,並用 showAtLocation 指定相對於按鈕的顯示位置即可。

Copyright © Linux教程網 All Rights Reserved