Mainactivity.XML
popupwindow.XML
MainActivity
package com.bwei.day_11_popupwindow;import android.app.Activity;import android.graphics.Color;import android.graphics.drawable.ColorDrawable;import android.graphics.drawable.Drawable;import android.os.Bundle;import android.view.Gravity;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.Button;import android.widget.PopupWindow;import android.widget.Toast;public class MainActivity extends Activity implements OnClickListener { private PopupWindow popupWindow; // private View view; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //加载popupwindow View view = View.inflate(MainActivity.this, R.layout.popupwindow, null); popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); // 设置popupwindow点击窗体外可以消失;但必须要给popupwindow设置背景 popupWindow.setOutsideTouchable(true); // 给popupwindow设置背景颜色 popupWindow.setBackgroundDrawable(new ColorDrawable(Color.YELLOW)); //监听 Button toast = (Button) view.findViewById(R.id.toast); Button close = (Button) view.findViewById(R.id.close); toast.setOnClickListener(this); close.setOnClickListener(this); } //3种显示 public void showpopup(View v) { System.out.println(popupWindow.isShowing()); // 判断popupwindow是否在显示 if (!popupWindow.isShowing()) { popupWindow.showAsDropDown(v); } } public void showpopup_two(View v) { // 判断popupwindow是否在显示 if (!popupWindow.isShowing()) { // 参数一:popupwindow显示时的参照控件,参数二:X轴的偏移量,参数三:Y轴的偏移量 popupWindow.showAsDropDown(v, 100, 200); } } public void showpopup_three(View v) { // 参数一:popupwindow的父窗体.参数二:popupwindow显示时的相对位置,参数三:X轴的偏移量,参数四:Y轴的偏移量 popupWindow.showAtLocation(v, Gravity.LEFT, 0, 0); } //popupWindow内部 @Override public void onClick(View v) { switch (v.getId()) { // 弹出吐司 case R.id.toast: Toast.makeText(MainActivity.this, "点击popupwindow内部按钮弹出的", 1).show(); break; // 关闭popupwindow case R.id.close: // 关闭popupwindows popupWindow.dismiss(); break; } }}