Skip to content

Instantly share code, notes, and snippets.

@Viyu
Last active August 29, 2015 13:57
Show Gist options
  • Save Viyu/9521561 to your computer and use it in GitHub Desktop.
Save Viyu/9521561 to your computer and use it in GitHub Desktop.
A encapsulated popup window which show given content view(mostly menus).
/**
*
* @author viyu
*
*/
public class MenuPopWindow extends PopupWindow implements OnClickListener {
private Activity mActivity = null;
private CustomView mContentView = null;
private TextView mItemQuit = null;
//
public MenuPopWindow(Activity activity) {
super(activity);
mActivity = activity;
initUI();
}
protected MenuPopWindow(Context context, AttributeSet attrs) {
super(context, attrs);
}
private void initUI() {
LayoutInflater mInflater = mActivity.getLayoutInflater();
mContentView = (CustomView) mInflater.inflate(R.layout.menu_pop_window, null);
//如果要用menu键来控制window,可以注册这个
mContentView.setKeyEventCallback(new KeyEventCallback() {
@Override
public void onMenuKeyDown() {
showPopWindow(....);
}
});
setContentView(mContentView);
//
mItemQuit = (TextView) mContentView.findViewById(R.id.menu_pop_window_quit);
mItemQuit.setOnClickListener(this);
//
setOutsideTouchable(true);
setFocusable(true);
//
mContentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
setWidth(mContentView.getMeasuredWidth());
setHeight(mContentView.getMeasuredHeight());
//
setBackgroundDrawable(...);
}
@Override
public void onClick(View v) {
if (v == mItemQuit) {
...
}
dismiss();
}
public void showPopWindow(View mHostView, xOff, yOff) {
//
if (isShowing()) {
dismiss();
return;
}
//
showAsDropDown(mHostView, xOff, yOff);
}
}
/**
*
* @author viyu
*
*/
public class CustomView extends LinearLayout {
private KeyEventCallback mKeyEventCallback = null;
public CustomView(Context context) {
super(context);
setFocusableInTouchMode(true);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
setFocusableInTouchMode(true);
}
public void setKeyEventCallback(KeyEventCallback keyEventCallback) {
mKeyEventCallback = keyEventCallback;
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
if (mKeyEventCallback != null) {
mKeyEventCallback.onMenuKeyDown();
}
}
return super.dispatchKeyEvent(event);
}
public interface KeyEventCallback {
public void onMenuKeyDown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment