private PopupWindow mPopWindow;
private void testPopupWindowType2() {
View contentView = getPopupWindowContentView();
mPopWindow = new PopupWindow(contentView,
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
// 如果不设置PopupWindow的背景,有些版本就会出现一个问题:无论是点击外部区域还是Back键都无法dismiss弹框
mPopWindow.setBackgroundDrawable(new ColorDrawable());
// 设置好参数之后再show
// popupWindow.showAsDropDown(mButton2); // 默认在mButton2的左下角显示
contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
/* int xOffset = mButton2.getWidth() / 2 - contentView.getMeasuredWidth() / 2;*/
LinearLayout popwind = (LinearLayout) findViewById(R.id.popwind);
mPopWindow.showAsDropDown(popwind, 740, 5); // 在mButton2的中间显示
/* mPopWindow.showAtLocation(popwind, Gravity.NO_GRAVITY,740,10);*/
}
private View getPopupWindowContentView() {
// 一个自定义的布局,作为显示的内容
int layoutId = R.layout.pop_window_layout; // 布局ID
View contentView = LayoutInflater.from(this).inflate(layoutId, null);
View.OnClickListener menuItemOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
/* Toast.makeText(v.getContext(), "Click " + ((TextView) v).getText(), Toast.LENGTH_SHORT).show();*/
if(((TextView) v).getText().equals("加好友")){
/* Intent intent=new Intent(MainActivity.this, AddfriendActivity.class);
startActivity(intent);*/
}
if(((TextView) v).getText().equals("创建群")){
/* Intent intent=new Intent(MainActivity.this, CreateGroupActivity.class);
startActivity(intent);*/
}
if (mPopWindow != null) {
mPopWindow.dismiss();
}
}
};
/* contentView.findViewById(R.id.addfriends).setOnClickListener(menuItemOnClickListener);
contentView.findViewById(R.id.AddGroup).setOnClickListener(menuItemOnClickListener);*/
return contentView;
}
estPopupWindowType2();//在点击处直接调用
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@mipmap/add_fridends_two"
android:orientation="vertical"
android:paddingBottom="2dp">
<TextView
android:id="@+id/addfriends"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="加好友"
android:textColor="@color/search"
android:layout_marginTop="28dp"
android:textSize="17sp"
android:gravity="center"/>
<TextView
android:id="@+id/AddGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="创建群"
android:textColor="@color/search"
android:layout_marginTop="32dp"
android:textSize="17sp"
android:gravity="center"/>
</LinearLayout>