package com.example.popupwindow; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.PopupWindow; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button myButton = findViewById(R.id.button); myButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onButtonShowPopupWindowClick(v); } }); } public void onButtonShowPopupWindowClick(View view) { // inflate the layout of the popup window LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); View popupView = inflater.inflate(R.layout.popup, null); // instance of button on the popup Button delete = popupView.findViewById(R.id.PopupBtn); delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // could close the window or do something else reset(); // shows an AlertDialog } }); // create the popup window int width = LinearLayout.LayoutParams.WRAP_CONTENT; int height = LinearLayout.LayoutParams.WRAP_CONTENT; boolean focusable = true; // lets taps outside the popup also dismiss it final PopupWindow popupWindow = new PopupWindow(popupView, width, height, focusable); // show the popup window // which view you pass in doesn't matter, it is only used for the window popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0); popupWindow.setFocusable(true); // dismiss the popup window when touched popupView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { popupWindow.dismiss(); // popup closes if you press outside of it return true; } }); } // example method that shows a confirmation dialog public void reset() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Confirm delete all data"); builder.setMessage("All data will be erased. Are you sure?"); builder.setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setNegativeButton("NO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } }