效果图
Demo
- Project:CombinedChartDemo
- File:MyPopupWindow.java
初始化
// 获取弹出的PopupWindow的界面
View mContentView = View.inflate(context, R.layout.popupwindow, null)
// 创建一个PopupWindow并默认获取焦点(如果没有焦点view无法监听到点击事件)
PopupWindow mPopupWindow = new PopupWindow(mContentView, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, true)
// ***给PopupWindow设置背景
mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT))
mPopupWindow.update()
显示
/** * 显示PopupWindow * * @param parent 父控件 */
public void showPopupWindow(View parent) {
int[] location = new int[2];
parent.getLocationInWindow(location);
mPopupWindow.showAtLocation(parent, Gravity.TOP | Gravity.START, location[0], location[1] + parent.getHeight());
}
隐藏
代码控制关闭
/** * 关闭PopupWindow */
public void dismiss() {
if (null != mPopupWindow && mPopupWindow.isShowing()) {
mPopupWindow.dismiss();
}
}
mPopupWindow.setOutsideTouchable(true);
返回按钮控制关闭
mContentView.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
dismiss();
return true;
default:
return false;
}
}
});
开关
/** * 开关 * @param parent 父控件 */
public void toggle(View parent) {
if (mPopupWindow.isShowing()) {
dismiss();
} else {
showPopupWindow(parent);
}
}
封装
package kong.qingwei.combinedchartdemo.view;
import android.content.Context;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;
import kong.qingwei.combinedchartdemo.R;
/** * Created by kqw on 2016/5/17. * MyPopupWindow */
public class MyPopupWindow extends PopupWindow implements View.OnKeyListener {
private PopupWindow mPopupWindow;
private final View mContentView;
public MyPopupWindow(Context context) {
mContentView = View.inflate(context, R.layout.popupwindow, null);
mContentView.setOnKeyListener(this);
mPopupWindow = new PopupWindow(mContentView, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
mPopupWindow.setOutsideTouchable(true);
}
/** * 显示PopupWindow * * @param parent 父控件 */
public void showPopupWindow(View parent) {
int[] location = new int[2];
parent.getLocationInWindow(location);
mPopupWindow.showAtLocation(parent, Gravity.TOP | Gravity.START, location[0], location[1] + parent.getHeight());
}
/** * 关闭PopupWindow */
public void dismiss() {
if (null != mPopupWindow && mPopupWindow.isShowing()) {
mPopupWindow.dismiss();
}
}
/** * 开关 * @param parent 父控件 */
public void toggle(View parent) {
if (mPopupWindow.isShowing()) {
dismiss();
} else {
showPopupWindow(parent);
}
}
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
dismiss();
return true;
default:
return false;
}
}
}
使用
MyPopupWindow myPopupWindow = new MyPopupWindow(context);
myPopupWindow.showPopupWindow(parentView);
myPopupWindow.toggle(parentView);