摘自:http://my.oschina.net/artshell/blog/422268
直接上代码
activity_popup_window_tooltip_text.xml
nav_up.xml (drawable)
tooltip_bg.xml (drawable)
popup_window_tooltip_layout.xml
Activity代码:
public class PopupWindowTooltipTextActivity extends ActionBarActivity {
private View contentView;
private PopupWindow tipWindow;
private Button anchor_view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_popup_window_tooltip_text);
anchor_view = (Button) findViewById(R.id.anchor_view);
contentView = getLayoutInflater().inflate(R.layout.popup_window_tooltip_layout, null);
tipWindow = new PopupWindow(this);
tipWindow.setTouchInterceptor(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
tipWindow.dismiss();
}
// 这个地方一定要返回false,你可能会说这里已经消费掉事件了啊应该返回true,参看PopupWindow的私有类PopupViewContainer
// 弹出的View都是交由这个类来管理的,因为它对onTouchEvent()这个回调方法已经提供了一些默认实现,当你是返回true,事件就在此被拦截
// 不会再继续派发了,所以onTouchEvent()无法被调用
return false;
}
});
anchor_view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tipWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
tipWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
tipWindow.setOutsideTouchable(true);
tipWindow.setTouchable(true);
tipWindow.setFocusable(true);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.easyicon_net);
// 某些博客说,当没有设置Background的时候,无论是触摸其他空白区还是back键都无法dismiss()掉这个PopupWindow
// 但我注释掉这段代码能dismiss(),有可能是个Bug,已经得google到修复
tipWindow.setBackgroundDrawable(new BitmapDrawable(getResources(),bitmap));
tipWindow.setContentView(contentView);
// 计算这个PopupWindow的显示位置
int[] screen_pos = new int[2];
anchor_view.getLocationOnScreen(screen_pos);
Rect anchor_rect = new Rect(screen_pos[0], screen_pos[1], screen_pos[0] + anchor_view.getWidth(), screen_pos[1] + anchor_view.getHeight());
contentView.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
int contentViewWidth = contentView.getMeasuredWidth();
int contentViewHeight = contentView.getMeasuredHeight();
int position_x = anchor_rect.centerX() - (contentViewWidth / 2);
int position_y = anchor_rect.bottom - (anchor_rect.height() / 2);
tipWindow.showAtLocation(anchor_view, Gravity.NO_GRAVITY, position_x, position_y);
}
});
}
}
这里再帖两个参考链接,希望对你有所帮助
http://www.cnblogs.com/mengdd/p/3569127.html 【Android PopupWindow的使用和分析】
http://michaelye1988.iteye.com/blog/1766629 【Popupwindow的使用】