天天看點

popupWindow 的一種實作寫法

/** drawableId 為popupwindow 中的圖檔Id, */
public static void showPopupWindow(Context context, Guide guide, 
	int drawableId, int x, int y) {
	
  final ViewGroup parent = (ViewGroup) ((Activity) context)
	.findViewById(android.R.id.content);
  LayoutInflater inflater = (LayoutInflater) 
	context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  View view = inflater.inflate(R.layout.operate_guide_popwindow, 
	null, false);
  LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams
	(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
  ImageView iv = new ImageView(context);
  lp.setMargins(x, y, 0, 0);
  iv.setLayoutParams(lp);
  iv.setBackgroundResource(drawableId);
  LinearLayout ll_content = (LinearLayout) view.findViewById(R.id.ll_content);
  boolean isVertical = false;
  
  if (context.getResources().getConfiguration().orientation 
	== Configuration.ORIENTATION_LANDSCAPE) {
   ll_content.setOrientation(LinearLayout.HORIZONTAL);
   isVertical = false;
  } else {
   ll_content.setOrientation(LinearLayout.VERTICAL);
   isVertical = true;
  }
  
  ll_content.addView(iv);
  if (context instanceof LadyDetailActivity) {
   ImageView iv2 = new ImageView(context);
   LinearLayout.LayoutParams lp2 = new LinearLayout
   .LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
   if (isVertical) {
    lp2.setMargins(x + 45, y / 2 + iv.getHeight(), 0, 0);
   } else {
    lp2.setMargins(x + iv.getWidth(), y, 0, 0);
   }
   
   iv2.setLayoutParams(lp2);
   iv2.setBackgroundResource(R.drawable.guide_swipe_left_or_right);
   ll_content.addView(iv2);
  }
  
  final PopupWindow mPopWin = new PopupWindow(view, 
	LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, true);
  mPopWin.setOutsideTouchable(true);
  mPopWin.setAnimationStyle(R.style.PopupAnimation);
  mPopWin.showAtLocation(parent, Gravity.CENTER, x, y);
  view.requestFocus();
  
  // 如果視窗已經顯示過,更改此值隻能在下一次顯示時起作用,
  //或者調用update() mPopWin.update();
  view.setOnClickListener(new View.OnClickListener() {
  
   @Override
   public void onClick(View v) {
    if (mPopWin != null) {
     mPopWin.dismiss();
    }
   }
   
  });
  
 }