Android进阶篇-PopupWindow的使用

/**
 * @author gongchaobin
 *
 * 自定义popuwindow
 * @version 2012-12-12
 */
public class MyPopuWindow {
	private LayoutInflater mInflater;
	private PopupWindow mPopupWindow;
	private View mView;
	private Button mBtn;
	
	/**
	 * @param context 上下文
	 * @param resId layout资源ID
	 * @param width popuwindow的宽
	 * @param height popuwindw的高
	 * @param view 显示位置相对的view 
	 */
	public MyPopuWindow(Context context,int resId,int width,int height,OnClickListener clickListener,View view){
		mInflater = LayoutInflater.from(context);
		mView = mInflater.inflate(resId, null);
		mPopupWindow = new PopupWindow(mView, width, height);
		
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        /*设置触摸外面时消失*/  
		mPopupWindow.setOutsideTouchable(true);
//        /*设置系统动画*/  
//        popupWindow.setAnimationStyle(R.style.PopupAnimation);
		mPopupWindow.update();
		mPopupWindow.setTouchable(true);
	      /*设置点击menu以外其他地方以及返回键退出*/  
		mPopupWindow.setFocusable(true);
		mPopupWindow.showAsDropDown(view);
		
		mBtn = (Button) mView.findViewById(R.id.button1);
		mBtn.setOnClickListener(clickListener);
		
	     /** 
         * 解决再次点击MENU键无反应问题   
         */
		mView.setFocusableInTouchMode(true);
		mView.setOnKeyListener(new OnKeyListener() {  
            public boolean onKey(View v, int keyCode, KeyEvent event) {  
                // TODO Auto-generated method stub  
                if ((keyCode == KeyEvent.KEYCODE_MENU)&&(mPopupWindow.isShowing())) { 
                	mPopupWindow.dismiss();
                    return true;  
                }else if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK){
                	mPopupWindow.dismiss();
                    return false;
                }
                return false;  
            }  
        });
	}
}

  

posted @ 2012-05-23 15:12  暗殇  阅读(532)  评论(0编辑  收藏  举报