package de.tudarmstadt.informatik.hostage.ui2.popup; import android.app.Activity; import android.content.Context; import android.graphics.Rect; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.LinearLayout; import android.widget.PopupWindow; /** * Created by Julien on 13.02.14. */ public abstract class AbstractPopup { public interface OnPopupItemClickListener { public void onItemClick(AbstractPopupItem item); } private PopupWindow popupWindow; private Activity context; private OnPopupItemClickListener onPopupItemClickListener; private LinearLayout rootView; private LayoutInflater lInf; abstract public int getLayoutId(); abstract void configureView(View view); public AbstractPopup(Context context, OnPopupItemClickListener listener) { super(); this.context = (Activity) context; this.onPopupItemClickListener = listener; this.popupWindow = new PopupWindow(context); this.popupWindow.setOutsideTouchable(true); this.popupWindow.setFocusable(true); this.lInf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void addItem(final AbstractPopupItem item) { View view = item.getItemView(); if (this.rootView == null){ this.rootView = (LinearLayout) lInf.inflate(this.getLayoutId(), null); this.configureView(this.rootView); } if (this.rootView != null){ this.rootView.addView(view); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onPopupItemClickListener.onItemClick(item); popupWindow.dismiss(); } }); } } public View getPopupView(){ return rootView; } public void showOnView(View view) { if (this.rootView == null){ this.rootView = (LinearLayout) lInf.inflate(this.getLayoutId(), null); } popupWindow.setContentView(rootView); Rect rectagle= new Rect(); Window window= this.context.getWindow(); window.getDecorView().getWindowVisibleDisplayFrame(rectagle); int[] position = new int[2]; view.getLocationOnScreen(position); rootView.measure(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT); int x = position[0] + (view.getWidth() / 2) - (rootView.getMeasuredWidth() / 2); int y = position[1] - rootView.getMeasuredHeight(); x = Math.min(0,x); x = Math.max(rectagle.width()-rootView.getMeasuredWidth(), x); y = Math.min(0,y); y = Math.max(rectagle.height()-rootView.getMeasuredHeight(), y); this.configureView(rootView); int smallBottomOffset = 10; popupWindow.setWidth(rootView.getMeasuredWidth()); popupWindow.setHeight(rootView.getMeasuredHeight() + smallBottomOffset); popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, x, y); } }