1、資源文件
app\src\main\res\layout下增加custom_pop_layout.xml
定義彈窗的控件資源。
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="match_parent"><ImageViewandroid:id="@+id/customPopView"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#ff000000" /><Buttonandroid:id="@+id/exampleButton"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="80dp"android:layout_marginStart="40dp"android:text="示例按鈕"app:layout_constraintStart_toStartOf="@id/customPopView"app:layout_constraintTop_toTopOf="@id/customPopView" />
</androidx.constraintlayout.widget.ConstraintLayout>
2、java代碼
CustomPopUtil初始化有下面幾點:
1)獲取資源文件的rootView,添加到系統管理器下,達到系統級彈窗效果,可在其他app上彈出。
2)params = new WindowManager.LayoutParams是用來設置彈窗的參數,包括大小、坐標、透明度等。后面可根據需要修改。
3)rootView.setVisibility(View.GONE)表示初始化隱藏。
4)需要彈出時,調用接口show(),如果彈出時,想要修改彈窗的界面參數,可在show接口里調用WindowManager.LayoutParams進一步定制。
import static android.content.Context.WINDOW_SERVICE;import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.graphics.PixelFormat;
import android.widget.Button;public class CustomPopUtil {private View rootView;private Button exampleButton;// 可增加其他ui控件@SuppressLint("InflateParams")public void init(Context context) {rootView = LayoutInflater.from(context).inflate(R.layout.custom_pop_layout, null);WindowManager windowManager = (WindowManager) context.getSystemService(WINDOW_SERVICE);WindowManager.LayoutParams params = null;if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {params = new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,PixelFormat.OPAQUE);}windowManager.addView(rootView, params);rootView.setVisibility(View.GONE);exampleButton = rootView.findViewById(R.id.exampleButton);exampleButton.setOnClickListener(v -> {// do some logic});}public void show() {rootView.setVisibility(View.VISIBLE);}public void hide() {rootView.setVisibility(View.GONE);}
}