首页 > 代码库 > popupWindow 用法总结 控制位置
popupWindow 用法总结 控制位置
android中的dialog,以及activiy形式的dialog均是模态对话框,对话框不消失时,不能对其他页面进行操作,也就是其他页面不能获得焦点。而PopupWindow是非模态对话框,对话框显示的时候,其他界面仍然可以获得焦点,仍然可以进行点击等操作,同时也可以对对话框进行点击等操作。
很好的例子就是输入法,通过查看源码就可以看到,其界面是几个popupwindow组成的。
三个关键设置
// 如果不设置PopupWindow的背景,有些版本就会出现一个问题:无论是点击外部区域还是Back键都无法dismiss弹框
popupWindow.setBackgroundDrawable(new ColorDrawable());
// setOutsideTouchable设置生效的前提是setTouchable(true)和setFocusable(false)
popupWindow.setOutsideTouchable(true);
// 设置为true之后,PopupWindow内容区域 才可以响应点击事件
popupWindow.setTouchable(true);
Activity
public class MainActivity extends ListActivity {
private PopupWindow pop;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] array = { "在指定view的正左下方,无偏移", //
"相对指定view正左下方,有偏移",//
"Gravity.NO_GRAVITY:相对屏幕左上角,注意包含状态栏区域",//
"Gravity.TOP:相对屏幕正上方居中",//
"pop不会偏移出屏幕,偏移值过大时取临界值",//
"Gravity.BOTTOM:相对屏幕正下方居中,注意包含虚拟按键区域",//
"Gravity.BOTTOM:此时yoff为正时表示向上偏移(而非向下偏移)",//
"出现在View的任意位置", };
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>(Arrays.asList(array))));
pop = new PopupWindow(this);
pop.setFocusable(true);//必备设置1
pop.setBackgroundDrawable(new ColorDrawable(0x00ff0000));//必备设置2
pop.setOutsideTouchable(true);//setFocusable(true)后这个设置就没用了
pop.setAnimationStyle(R.style.popAniStyle);//设置动画所对应的style
}
private boolean b;
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
b = !b;
if (b) pop.setContentView(LayoutInflater.from(this).inflate(R.layout.view1, null));
else pop.setContentView(LayoutInflater.from(this).inflate(R.layout.view2, null));
switch (position) {
case 0://在指定view的正左下方,无偏移
pop.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);//必须设置宽和高
pop.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
pop.showAsDropDown(v);
break;
case 1://相对指定view正左下方的位置,有偏移
pop.setWidth(DensityUtils.getScreenWidth(this) - 20);
pop.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
pop.showAsDropDown(v, 20, 10);
break;
case 2://相对于父控件的某个相对位置的偏移,默认的Gravity.NO_GRAVITY的参照物为【屏幕左上角】,注意包含状态栏区域
case 3://若偏移值大于pop偏出屏幕的临界值,将取临界值。也即pop不可能会偏移出屏幕
case 4://不管view设置的是哪一个,参照物都是整个屏幕的根布局
pop.setWidth(DensityUtils.getScreenWidth(this) - 20);
pop.setHeight(20);
if (position == 2) pop.showAtLocation(v, Gravity.NO_GRAVITY, 20, DensityUtils.getStatusBarHeight(this) + 10);//Gravity.NO_GRAVITY:相对屏幕左上角
else if (position == 3) pop.showAtLocation(v, Gravity.TOP, 10, DensityUtils.getStatusBarHeight(this) + 10);//Gravity.TOP:相对屏幕正上方居中
else pop.showAtLocation(v, Gravity.TOP, 100, DensityUtils.getStatusBarHeight(this));//临界值为 20/2=10,偏移值大于10时仅偏移10
break;
case 5://Gravity.BOTTOM:相对屏幕正下方居中,注意包含虚拟按键区域,并且此时yoff为正时表示向上偏移(而非向下偏移)
case 6://
pop.setWidth(DensityUtils.getScreenWidth(this) - 20);
pop.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
if (position == 5) pop.showAtLocation(v, Gravity.BOTTOM, 0, DensityUtils.getBottomBarHeight(this));//Gravity.BOTTOM:相对屏幕正下方居中
else if (position == 6) pop.showAtLocation(v, Gravity.BOTTOM, -10, DensityUtils.getBottomBarHeight(this) + 10);//此时yoff为正时表示向上偏移
break;
case 7://
startActivity(new Intent(this, SecondActivity.class));
break;
}
}
}Activity2
public class SecondActivity extends Activity {
private int num = 0;
private PopupWindow pop;
private int[] location = new int[2];;
private View contentView;
@SuppressLint("InflateParams")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
contentView = LayoutInflater.from(this).inflate(R.layout.view2, null);
pop = new PopupWindow(contentView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
pop.setFocusable(true);//必备设置1
pop.setBackgroundDrawable(new ColorDrawable(0x00ff0000));//必备设置2
pop.setOutsideTouchable(true);//setFocusable(true)后这个设置就没用了
pop.setAnimationStyle(R.style.popAniStyle);//设置动画所对应的style
}
public void onClick(View v) {
v.getLocationOnScreen(location);// 获取锚点View在屏幕上的左上角坐标位置
switch (num % 4) {
case 0://右下
pop.showAtLocation(v, Gravity.NO_GRAVITY, location[0] + v.getWidth(), location[1] + v.getHeight());
break;
case 1://右上
pop.showAtLocation(v, Gravity.NO_GRAVITY, location[0] + v.getWidth(), location[1] - contentView.getHeight());
break;
case 2://左上
pop.showAtLocation(v, Gravity.NO_GRAVITY, location[0] - contentView.getWidth(), location[1] - contentView.getHeight());
break;
default://左下
pop.showAtLocation(v, Gravity.NO_GRAVITY, location[0] - contentView.getWidth(), location[1] + v.getHeight());
break;
}
Toast.makeText(this, num % 4 + "", Toast.LENGTH_SHORT).show();
num++;
}
}工具类
public class DensityUtils {
//******************************************************************************************
// 单位转换
//******************************************************************************************
/**像素密度*/
public static float getDisplayMetrics(Context context) {
return context.getResources().getDisplayMetrics().density;
}
/** dp 转成为 px */
public static int dp2px(Context context, float dpValue) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, context.getResources().getDisplayMetrics());
}
/** px 转成为 dp */
public static int px2dp(Context context, float pxValue) {
return (int) (pxValue / getDisplayMetrics(context) + 0.5f);
}
/** sp转px */
public static int sp2px(Context context, float spVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal, context.getResources().getDisplayMetrics());
}
/** px转sp */
public static float px2sp(Context context, float pxVal) {
return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
}
//******************************************************************************************
// 屏幕宽高
//******************************************************************************************
/** 获取屏幕宽 */
public static int getScreenWidth(Context context) {
DisplayMetrics metric = new DisplayMetrics();
((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metric);
return metric.widthPixels;
}
/** 获取屏幕高,包含状态栏,但不包含虚拟按键,如1920屏幕只有1794 */
public static int getScreenHeight(Context context) {
DisplayMetrics metric = new DisplayMetrics();
((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metric);
return metric.heightPixels;
}
/** 获取屏幕宽 */
public static int getScreenWidth2(Context context) {
Point point = new Point();
((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getSize(point);
return point.x;
}
/** 获取屏幕高,包含状态栏,但不包含某些手机最下面的【HOME键那一栏】,如1920屏幕只有1794 */
public static int getScreenHeight2(Context context) {
Point point = new Point();
((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getSize(point);
return point.y;
}
/** 获取屏幕原始尺寸高度,包括状态栏以及虚拟功能键高度 */
public static int getAllScreenHeight(Context context) {
Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
try {
DisplayMetrics displayMetrics = new DisplayMetrics();
Method method = Class.forName("android.view.Display").getMethod("getRealMetrics", DisplayMetrics.class);
method.invoke(display, displayMetrics);
return displayMetrics.heightPixels;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
//******************************************************************************************
// 状态栏、标题栏、虚拟按键
//******************************************************************************************
/** 状态栏高度,单位px,一般为25dp */
public static int getStatusBarHeight(Context context) {
int height = 0;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
height = context.getResources().getDimensionPixelSize(resourceId);
}
return height;
}
/** 状态栏高度,单位px,【注意】要在onWindowFocusChanged中获取才可以 */
public static int getStatusBarHeight2(Activity activity) {
Rect rect = new Rect();
//DecorView是Window中的最顶层view,可以从DecorView获取到程序显示的区域,包括标题栏,但不包括状态栏。所以状态栏的高度即为显示区域的top坐标值
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
return rect.top;
}
/**标题栏的高度,【注意】要在onWindowFocusChanged中获取才可以*/
public static int getTitleBarHeight(Activity activity) {
int contentTop = activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
return contentTop - getStatusBarHeight(activity);
}
/**获取 虚拟按键的高度 */
public static int getBottomBarHeight(Context context) {
return getAllScreenHeight(context) - getScreenHeight(context);
}
}常用API
构造方法
- public PopupWindow(View contentView)
- public PopupWindow(Context context)
- public PopupWindow(View contentView, int width, int height)
- public PopupWindow(View contentView, int width, int height, boolean focusable)
参数说明
- contentView为要显示的view;PopupWindow没有默认布局,它不会像AlertDialog那样只setTitle就能弹出来一个框,所以contentView必须设置。
- width和height为要显示的view的宽和高,值为像素值或MATCHT_PARENT、WRAP_CONTENT;如果View是从xml得到的,那么xml的第一层view的大小属性将被忽略;必须设置宽和高,否则显示不出来。
- focusable为是否能获得焦点
举例
View contentView = LayoutInflater.from(this).inflate(R.layout.popuplayout, null);
方法1:PopupWindow popupWindow = new PopupWindow(contentview,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
方法2:PopupWindow popupWindow = new PopupWindow(contentview);
方法3:PopupWindwo popWnd = PopupWindow (context);
popWnd.setContentView(contentView);
popupWindow.setWidth(LayoutParams.MATCHT_PARENT);
popupWindow.setHeight(LayoutParams.WRAP_CONTENT);
show方法
- showAsDropDown(View anchor) 相对某个控件的位置(正左下方),无偏移。最终调用的是下面的方法
- showAsDropDown(View anchor, int xoff, int yoff) 相对某个控件的位置,有偏移,xoff表示x轴的偏移,正值表示向左,负值表示向右;yoff表示相对y轴的偏移,正值是向下,负值是向上;最终调用的是下面的方法
- showAsDropDown(View anchor, int xoff, int yoff, int gravity) 【注:这个方法貌似不起作用】相对某个控件的某个位置,有偏移。gravity的默认值为DEFAULT_ANCHORED_GRAVITY= Gravity.TOP | Gravity.START
- showAtLocation(View parent, int gravity, int x, int y) 相对于父控件(不管view设置的是哪一个,参照物都是整个屏幕的根布局)的某个位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以设置偏移或无偏移。
/**
* Displays the content view in a popup window anchored to the corner of
* another view. The window is positioned according to the specified
* gravity and offset by the specified x and y coordinates.
* <p>
* If there is not enough room on screen to show the popup in its entirety,
* this method tries to find a parent scroll view to scroll. If no parent
* view can be scrolled, the specified vertical gravity will be ignored and
* the popup will anchor itself such that it is visible.
* <p>
* If the view later scrolls to move <code>anchor</code> to a different
* location, the popup will be moved correspondingly.
*
* @param anchor the view on which to pin the popup window
* @param xoff A horizontal offset from the anchor in pixels
* @param yoff A vertical offset from the anchor in pixels
* @param gravity Alignment of the popup relative to the anchor
*
* @see #dismiss()
*/
public void showAsDropDown(View anchor, int xoff, int yoff, int gravity)
/**
* <p>
* Display the content view in a popup window at the specified location. If the popup window
* cannot fit on screen, it will be clipped. See {@link android.view.WindowManager.LayoutParams}
* for more information on how gravity and the x and y parameters are related. Specifying
* a gravity of {@link android.view.Gravity#NO_GRAVITY} is similar to specifying
* <code>Gravity.LEFT | Gravity.TOP</code>.
* </p>
*
* @param parent a parent view to get the {@link android.view.View#getWindowToken()} token from
* @param gravity the gravity which controls the placement of the popup window
* @param x the popup‘s x location offset
* @param y the popup‘s y location offset
*/
public void showAtLocation(View parent, int gravity, int x, int y)
showAtLocation的parent参数可以很随意,只要是activity中的view都可以。
setFocusable
setFocusable(boolean focusable) 设置PopupWindow是否获取焦点
/**
* <p>Changes the focusability of the popup window. When focusable, the
* window will grab the focus from the current focused widget if the popup
* contains a focusable {@link android.view.View}. By default a popup
* window is not focusable.</p>
*
* <p>If the popup is showing, calling this method will take effect only
* the next time the popup is shown or through a manual call to one of
* the {@link #update()} methods.</p>
*
* @param focusable true if the popup should grab focus, false otherwise.
*
* @see #isFocusable()
* @see #isShowing()
* @see #update()
*/
public void setFocusable(boolean focusable) {
mFocusable = focusable;
}
setOutsideTouchable
/**
* <p>Controls whether the pop-up will be informed of touch events outside
* of its window. This only makes sense for pop-ups that are touchable
* but not focusable, which means touches outside of the window will
* be delivered to the window behind. The default is false.</p>
*
* <p>If the popup is showing, calling this method will take effect only
* the next time the popup is shown or through a manual call to one of
* the {@link #update()} methods.</p>
*
* @param touchable true if the popup should receive outside
* touch events, false otherwise
*
* @see #isOutsideTouchable()
* @see #isShowing()
* @see #update()
*/
public void setOutsideTouchable(boolean touchable) {
mOutsideTouchable = touchable;
}
2017-2-20
附件列表
popupWindow 用法总结 控制位置
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。