PopupWindowFactory.java
3.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package com.cnlive.im.ui;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
/**
* Created by Lynn on 2017/7/21.
*/
public class PopupWindowFactory {
private Context mContext;
private PopupWindow mPop;
/**
* @param context 上下文
* @param view PopupWindow显示的布局文件
*/
public PopupWindowFactory(Context context, View view) {
this(context, view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
/**
* @param context 上下文
* @param view PopupWindow显示的布局文件
* @param width PopupWindow的宽
* @param height PopupWindow的高
*/
public PopupWindowFactory(Context context, View view, int width, int height) {
init(context, view, width, height);
}
private void init(Context context, View view, int width, int height) {
this.mContext = context;
//下面这两个必须有
view.setFocusable(true);
view.setFocusableInTouchMode(true);
//PopupWindow(布局,宽度、高度)
mPop = new PopupWindow(view, width, height, true);
mPop.setFocusable(true);
mPop.setOutsideTouchable(false);
//重写onKeyListener,按返回键消失
view.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if (i == KeyEvent.KEYCODE_BACK) {
mPop.dismiss();
return true;
}
return false;
}
});
// 点击其他地方消失
view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (mPop != null && mPop.isShowing()) {
// mPop.dismiss();
return true;
}
return false;
}
});
}
public PopupWindow getPopupWindow() {
return mPop;
}
/**
* 以触发弹出窗的view为基准,出现在view的内部上面,弹出的pop_view左上角正对view的左上角
*
* @param parent view
* @param gravity 在view的什么位置Gravity.CENTER、Gravity.TOP......
* @param x 与控件的x坐标距离
* @param y 与控件的y坐标距离
*/
public void showAtLocation(View parent, int gravity, int x, int y) {
if (mPop.isShowing()) {
return;
}
mPop.showAtLocation(parent, gravity, x, y);
}
/**
* 以触发弹出窗的view为基准,出现在view的正下方,弹出的pop_view左上角正对view的左下角
*
* @param anchor view
*/
public void showAsDropDown(View anchor) {
showAsDropDown(anchor, 0, 0);
}
/**
* 以触发弹出窗的view为基准,出现在view的正下方,弹出的pop_view左上角正对view的左下角
*
* @param anchor view
* @param xoff 与view的x坐标距离
* @param yoff 与view的y坐标距离
*/
public void showAsDropDown(View anchor, int xoff, int yoff) {
if (mPop.isShowing()) {
return;
}
mPop.showAsDropDown(anchor, xoff, yoff);
}
/**
* 隐藏popupwindow
*/
public void dismiss() {
if (mPop.isShowing()) {
mPop.dismiss();
}
}
}