您的位置:首页 > 运维架构

PopupWindow 弹出在控件上

2017-09-28 18:18 232 查看
popupWindow的布局文件popup.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_parent"
android:layout_height="wrap_content"
android:background="#206d95e5"
android:orientation="vertical" >

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="popupWindow"
android:textSize="16sp" />

<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="button"
android:textSize="16sp" />

</LinearLayout>


Activity中弹出PopupWindow

public void showPopupWindow(View v){

View contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.popup, null);
Button button = (Button) contentView.findViewById(R.id.btn);
final PopupWindow popupWindow = new PopupWindow(contentView,
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
popupWindow.setTouchable(true);

button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "onclick==action",
Toast.LENGTH_SHORT).show();
}
});

//检测屏幕消失的事件
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
Log.d("Chunna.zheng","popupwindow消失啦!");
}
});

// 如果不设置PopupWindow的背景,无论是点击外部区域还是Back键都无法dismiss弹框
popupWindow.setBackgroundDrawable(getResources().getDrawable(
R.mipmap.ic_launcher));

//获取自身的长宽高
contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int popupHeight = contentView.getMeasuredHeight();
int popupWidth = contentView.getMeasuredWidth();

//获取控件在屏幕上的位置,并赋值给location数组
int[] location = new int[2];
v.getLocationOnScreen(location);

//在控件上方显示
popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, (location[0]), location[1] - popupHeight/2);

// 如果要在控件下方显示,则使用这个方法
//popupWindow.showAsDropDown(v);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: