Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 技術基礎

PopupWindow 實作:做出浮動式圖示選單

編輯:Android 技術基礎

PopupWindow 是一種阻塞式的彈出視窗——在關掉它之前,原本的程式流程會停在這裡等待。它能浮動在當前 Activity 的任何位置,不受版面結構限制,因此常被拿來做「按一下選單鍵,浮出一排圖示」這類效果。

一、準備圖片資源

先把 icon_menu_addto.png、icon_menu_audioinfo.png、icon_menu_findlrc.png、icon_menu_scan.png 四張圖片複製到 res/drawable-hdpi 資料夾。

二、版面配置

1. 主視窗 activity_main.xml

主畫面只需要一個可供定位用的 TextView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hello" />
</LinearLayout>

2. 彈出視窗背景 framestyle.xml

於 res/drawable-hdpi 建立 framestyle.xml,用 shape 標籤畫出半透明白色外框與圓角,這裡的 <corners> 就是圓弧效果的來源:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <solid android:color="#b4000000" />
    <stroke android:width="2.0dip"
            android:color="#b4ffffff"
            android:dashWidth="3.0dip"
            android:dashGap="0.0dip" />
    <padding android:left="7.0dip"
             android:top="7.0dip"
             android:right="7.0dip"
             android:bottom="7.0dip" />
    <corners android:radius="8.0dip" />
</shape>

3. 選單內容 menu.xml

於 res/layout 建立 menu.xml,用 GridView 排列圖示並套用剛才的背景樣式:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent">

    <GridView android:id="@+id/menuGridChange"
        android:background="@drawable/framestyle"
        android:padding="5.0dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_gravity="center"
        android:horizontalSpacing="10.0dip"
        android:verticalSpacing="3.0dip"
        android:stretchMode="columnWidth"
        android:columnWidth="60.0dip"
        android:numColumns="auto_fit" />
</LinearLayout>

三、程式實作

這裡的做法是攔截系統選單鍵:按下時與其顯示預設選單,不如換成我們自己的 PopupWindow。關鍵在 onMenuOpened() 回傳 false,系統就不會再畫出 onCreateOptionsMenu() 裡的內容。

public class MainActivity extends Activity {

    private int[] resArray = {
        R.drawable.icon_menu_addto, R.drawable.icon_menu_audioinfo,
        R.drawable.icon_menu_findlrc, R.drawable.icon_menu_scan
    };
    private String[] title = {"添加", "信息", "搜索", "查看"};

    private PopupWindow pw = null;

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("");
        return super.onCreateOptionsMenu(menu);
    }

    public boolean onMenuOpened(int featureId, Menu menu) {
        if (pw != null) {
            if (pw.isShowing()) {
                pw.dismiss();                       // 已經開著就收起來
            } else {
                pw.showAtLocation(findViewById(R.id.hello), Gravity.CENTER, 0, 300);
            }
        } else {
            LayoutInflater inflater = (LayoutInflater)
                    this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = inflater.inflate(R.layout.menu, null);
            GridView grid1 = (GridView) view.findViewById(R.id.menuGridChange);
            grid1.setAdapter(new ImageAdapter(this));

            pw = new PopupWindow(view,
                    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            pw.showAtLocation(findViewById(R.id.hello), Gravity.CENTER, 0, 300);
        }
        // 回傳 false,系統便不會執行 onCreateOptionsMenu 裡的選單
        return false;
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            pw.dismiss();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    // GridView 用的轉接器:圖片在上、文字在下
    public class ImageAdapter extends BaseAdapter {
        private Context context;
        public ImageAdapter(Context context) { this.context = context; }

        @Override public int getCount() { return resArray.length; }
        @Override public Object getItem(int arg0) { return resArray[arg0]; }
        @Override public long getItemId(int arg0) { return arg0; }

        @Override
        public View getView(int arg0, View arg1, ViewGroup arg2) {
            LinearLayout linear = new LinearLayout(context);
            linear.setOrientation(LinearLayout.VERTICAL);

            ImageView iv = new ImageView(context);
            iv.setImageBitmap(((BitmapDrawable)
                    context.getResources().getDrawable(resArray[arg0])).getBitmap());

            TextView tv = new TextView(context);
            tv.setText(title[arg0]);

            LinearLayout.LayoutParams params =
                    new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            params.gravity = Gravity.CENTER;

            linear.addView(iv, params);
            linear.addView(tv, params);
            return linear;
        }
    }
}

幾個實作細節值得留意:showAtLocation() 的第一個參數只是用來決定座標原點的參考 View,並非要彈在它正下方;若要貼齊某個元件,則該改用 showAsDropDown()。另外別忘了在返回鍵中呼叫 dismiss(),否則使用者會找不到關掉浮窗的方法。

四、執行結果

按下選單鍵後,帶有圓角邊框的四格圖示選單會浮現在畫面中央。

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