按照我对popwindow的理解,他是一个自定义 的对话框。
使用方法,需要一个自定义的xml文件,就是弹出来是什么样,自行设置。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="match_parent" android:layout_height="@dimen/fifty" android:text="@string/mydialog" android:gravity="center" /> <TextView android:layout_width="match_parent" android:layout_height="@dimen/fifty" android:id="@+id/textdialog" android:text="@string/textdialog" android:gravity="center" /> </LinearLayout>
2 在需要显示这个对话框的时候调用下面的方法:
public void showMyDialog(View view) { View contentView = LayoutInflater.from(MainActivity.this).inflate( R.layout.pop_window, null); textDialog = (TextView) contentView.findViewById(R.id.textdialog); textDialog.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "button is pressed", Toast.LENGTH_SHORT).show(); } }); final PopupWindow popupWindow = new PopupWindow(contentView, ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, true); popupWindow.setTouchable(true); popupWindow.setTouchInterceptor(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return false; // 这里如果返回true的话,touch事件将被拦截 // 拦截后 PopupWindow的onTouchEvent不被调用,这样点击外部区域无法dismiss } }); // 如果不设置PopupWindow的背景,无论是点击外部区域还是Back键都无法dismiss弹框 // 我觉得这里是API的一个bug popupWindow.setBackgroundDrawable(getResources().getDrawable( R.drawable.selectmenu_bg_downward)); // 设置好参数之后再show popupWindow.showAsDropDown(view,300,200); }
最主要是showAsDropDown()方法
view 是显示谁?
300 x轴方向,正数是x轴向右偏移多少,负数是x轴向左偏移多少;
200 y轴方向,正数是y轴向下偏移多少,负数是y轴向左偏移多少;