1. activity_main.xml
<span style="font-family:Microsoft YaHei;font-size:12px;"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.popupwindow.MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="点击弹出PopupWindow" />
</RelativeLayout></span>
2.定义popupWindow视图
新建popup_window.xml
<span style="font-family:Microsoft YaHei;font-size:12px;"><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:paddingBottom="8dp" >
<Button
android:id="@+id/textView2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="取消" />
</RelativeLayout></span>
<span style="font-family:Microsoft YaHei;font-size:12px;">public class MainActivity extends Activity {
private Button button;
PopupWindow popupWindow;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
intiPopup();// 初始化PopupWindow
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//设置PopupWind的显示位置。
<span style="color:#ff0000;">popupWindow.showAtLocation(button, Gravity.NO_GRAVITY,
(int) button.getX(), (int) button.getY());</span>
}
});
}
private void intiPopup() {
// 加载PopupWindow的布局文件
View contentView = LayoutInflater.from(getApplicationContext())
.inflate(R.layout.popup_window, null, false);
// 声明一个对话框
popupWindow = new PopupWindow(null, LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, true);
// 为自定义的对话框设置自定义布局
popupWindow.setContentView(contentView);
showAsDropDown(anchor, xoff, yoff);
// 需要设置一下此参数,点击外边可消失
popupWindow.setBackgroundDrawable(getResources().getDrawable(
R.drawable.quespage_center_normal_bg));
// 设置点击窗口外边窗口消失
popupWindow.setOutsideTouchable(true);
// 设置此参数获得焦点,否则无法点击
popupWindow.setFocusable(true);
Button buttonC = (Button) contentView.findViewById(R.id.textView2);
buttonC.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
popupWindow.dismiss();// 关闭PopupWindow
}
});
}
}</span>
关于popupWindow显示位置的详解:
1.showAsDropDown(anchor);
2.showAsDropDown(anchor, xoff, yoff);
3.showAtLocation(parent, gravity, x, y);
parent:传你当前Layout的id;
gravity:Gravity.BOTTOM(以屏幕左下角为参照)... 偏移量会以它为基准点 当x y为0,0是出现在底部居中