【Android - 進階】之PopupWindow的使用


  創建一個類繼承自PopupWindow,編寫自定義的PopupWindow類。示例代碼如下:

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

/**
 * 自定義的PopupWindow
 */
public class MyPopWindow extends PopupWindow {

    public MyPopWindow(Activity context) {
        // 通過layout的id找到布局View
        View contentView = LayoutInflater.from(context).inflate(R.layout.pop_custom, null);
        // 獲取PopupWindow的寬高
        int h = context.getWindowManager().getDefaultDisplay().getHeight();
        int w = context.getWindowManager().getDefaultDisplay().getWidth();
        // 設置PopupWindow的View
        this.setContentView(contentView);
        // 設置PopupWindow彈出窗體的寬高
        this.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        // 設置PopupWindow彈出窗體可點擊(下面兩行代碼必須同時出現)
        this.setFocusable(true);
        this.setOutsideTouchable(true); // 當點擊外圍的時候隱藏PopupWindow
        // 刷新狀態
        this.update();
        // 設置PopupWindow的背景顏色為半透明的黑色
        ColorDrawable dw = new ColorDrawable(Color.parseColor("#66000000"));
        this.setBackgroundDrawable(dw);
        // 設置PopupWindow彈出窗體動畫效果
        this.setAnimationStyle(R.style.PopWindowAnimStyle);

        // 這里也可以從contentView中獲取到控件,並為它們綁定控件
    }

    // 顯示PopupWindow,有兩種方法:showAsDropDown、showAtLocation
    public void showPopupWindow(View parent) {
        if (!this.isShowing()) {
            // showAsDropDown方法,在parent下方的(x,y)位置顯示,x、y是第二和第三個參數
            // this.showAsDropDown(parent, parent.getWidth() / 2 - 400, 18);

            // showAtLocation方法,在parent的某個位置參數,具體哪個位置由后三個參數決定
            this.showAtLocation(parent, Gravity.CENTER, 0, 0);
        } else {
            this.dismiss();
        }
    }
}

  調用代碼:

MyPopWindow popWindow = new MyPopWindow(MainActivity.this);
popWindow.showPopupWindow(new View(MainActivity.this));

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM