Android入门之弹出式对话框的实现

  package org.mk.android.demopopupdialog;

  import androidx.appcompat.app.AppCompatActivity;

  import android.content.Context;

  import android.graphics.drawable.ColorDrawable;

  import android.os.Bundle;

  import android.view.LayoutInflater;

  import android.view.MotionEvent;

  import android.view.View;

  import android.view.ViewGroup;

  import android.widget.Button;

  import android.widget.PopupWindow;

  import android.widget.Toast;

  public class MainActivity extends AppCompatActivity {

  private Button btnPopWindow;

  private Context ctx;

  @Override

  protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);

  ctx=MainActivity.this;

  btnPopWindow=(Button)findViewById(R.id.btnPopWindow);

  btnPopWindow.setOnClickListener(new View.OnClickListener() {

  @Override

  public void onClick(View view) {

  popWindow(view);

  }

  });

  }

  private void popWindow(View v) {

  View subDlgView = LayoutInflater.from(ctx).inflate(R.layout.item_popup,

  null, false);

  Button btnTom = (Button) subDlgView.findViewById(R.id.btnTom);

  Button btnJerry = (Button) subDlgView.findViewById(R.id.btnJerry);

  //1.构造一个PopupWindow,参数依次是加载的View,宽高

  final PopupWindow popWindow = new PopupWindow(subDlgView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

  //这些为了点击非PopupWindow区域,PopupWindow会消失的,如果没有下面的

  //代码的话,你会发现,当你把PopupWindow显示出来了,无论你按多少次后退键

  //PopupWindow并不会关闭,而且退不出程序,加上下述代码可以解决这个问题

  popWindow.setTouchable(true);

  popWindow.setTouchInterceptor(new View.OnTouchListener() {

  @Override

  public boolean onTouch(View v, MotionEvent event) {

  return false;

  // 这里如果返回true的话,touch事件将被拦截

  // 拦截后 PopupWindow的onTouchEvent不被调用,这样点击外部区域无法dismiss

  }

  });

  popWindow.setBackgroundDrawable(new ColorDrawable(0x00000000)); //要为popWindow设置一个背景才有效

  //设置popupWindow显示的位置,参数依次是参照View,x轴的偏移量,y轴的偏移量

  popWindow.showAsDropDown(v, 50, 0);

  //设置popupWindow里的按钮的事件

  btnTom.setOnClickListener(new View.OnClickListener() {

  @Override

  public void onClick(View v) {

  Toast.makeText(MainActivity.this, "你点击了Tom, Tom吃Jerry", Toast.LENGTH_SHORT).show();

  }

  });

  btnJerry.setOnClickListener(new View.OnClickListener() {

  @Override

  public void onClick(View v) {

  Toast.makeText(MainActivity.this, "你点击了Jerry, Jerry揍Tom", Toast.LENGTH_SHORT).show();

  popWindow.dismiss();

  }

  });

  }

  }