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

Android 長按彈出自定義選項框並執行操作的完整實作

編輯:關於 Android 程式設計

本文示範如何在 Android 中實作「長按某個 View 後彈出選項框,點擊選項執行對應操作」的效果。

核心程式碼

private void showPopWindows(View v) {
    /** 彈窗內容 View */
    View mPopView = LayoutInflater.from(this).inflate(R.layout.popup, null);
    final PopupWindow mPopWindow = new PopupWindow(mPopView,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT, true);

    /** 設定背景(不設背景則外部點擊不會消失) */
    mPopWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

    /** 關鍵:先測量彈窗實際寬高,才能算準顯示位置 */
    mPopView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
    int popupWidth = mPopView.getMeasuredWidth();
    int popupHeight = mPopView.getMeasuredHeight();

    /** 取得觸發 View 在螢幕上的位置 */
    int[] location = new int[2];
    v.getLocationOnScreen(location);

    /** 讓彈窗水平居中於觸發 View 上方 */
    mPopWindow.showAtLocation(v, Gravity.NO_GRAVITY,
            (location[0] + v.getWidth() / 2) - popupWidth / 2,
            location[1] - popupHeight);
    mPopWindow.update();

    final String copyTxt = (String) v.getTag();
    mPopView.findViewById(R.id.tv_copy_txt).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            copyToClip(copyTxt);
            if (mPopWindow != null) {
                mPopWindow.dismiss();
            }
        }
    });
}

這裡有兩個容易忽略的細節。第一,PopupWindow 使用 WRAP_CONTENT 時,必須先呼叫 measure 才能取得真實寬高,否則無法正確計算居中偏移。第二,呼叫 showAtLocation 之後補一次 update(),能確保位置在測量完成後被重新套用。

彈窗版面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/pop_bg" >

    <TextView
        android:id="@+id/tv_copy_txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:gravity="center"
        android:text="復制邀請碼"
        android:textColor="@android:color/white"
        android:textSize="12sp" />
</LinearLayout>

效果

依據上面的計算方式,你可以自由調整偏移量,讓彈窗出現在觸發 View 的上方、下方或側邊。若要有多個選項,只要在 LinearLayout 中垂直排列多個 TextView,並各自綁定點擊事件即可。

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