导语
PopupWindow这个类用来实现一个弹出框,自定义布局,这个弹出框是悬浮在当前activity之上的,相对dialog自由度大,小型悬浮弹框比较有优势。
PopupWindow小案例
public class MainActivity extends Activity {
private Context mContext = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showPopupWindow(view);
}
});
}
private void showPopupWindow(View view) {
// 一个自定义的布局,作为显示的内容
View contentView = LayoutInflater.from(mContext).inflate(
R.layout.pop_window, null);
// 设置按钮的点击事件
Button button = (Button) contentView.findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mContext, "button is pressed",
Toast.LENGTH_SHORT).show();
}
});
final PopupWindow popupWindow = new PopupWindow(contentView,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
popupWindow.setTouchable(true);
popupWindow.setTouchInterceptor(new 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);
}
}
案例说明
上面代码中,布局文件XML中有一个TextView和一个Button,Button点击后显示Toast,如图:PopupWindow自带BUG:
第一次实现的时候遇到了问题,就是弹出框不会在按下Back键的时候消失,点击弹框外区域也没有正常消失,搜索了一下,都说只要设置背景就好了。然后我就找了个图片,果然弹框能正常dismiss了(见注释)。
1、showAtLocation()显示在指定位置,有两个方法重载:
public void showAtLocation(View parent, int gravity, int x, int y)
public void showAtLocation(IBinder token, int gravity, int x, int y)
public void showAsDropDown(View anchor)
public void showAsDropDown(View anchor, int xoff, int yoff)
public void showAsDropDown(View anchor, int xoff, int yoff, int gravity)
PopupWindow显示位置
两种方式:
1、showAtLocation()显示在指定位置,有两个方法重载:
public void showAtLocation(View parent, int gravity, int x, int y)
public void showAtLocation(IBinder token, int gravity, int x, int y)
2、showAsDropDown()显示在一个参照物View的周围,有三个方法重载:
public void showAsDropDown(View anchor)
public void showAsDropDown(View anchor, int xoff, int yoff)
public void showAsDropDown(View anchor, int xoff, int yoff, int gravity)