PopupWindow之前已经学习过了,可以查看教程[
PopupWindow的一些干货
先做个简单效果:PopupWindow显示在按钮下方
PopupwindowActivity
public class PopupwindowActivity extends AppCompatActivity {
PopupWindow popupWindow;
Button btn_add;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_popupwindow);
btn_add = findViewById(R.id.btn_add);
btn_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//popupwindow的布局
View popupView = View.inflate(PopupwindowActivity.this,R.layout.layout_more,null);
popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
//根据点击的view显示
popupWindow.showAsDropDown(view,0,0);
}
});
}
}
布局activity_popupwindow即一个Button
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<Button
android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="添加好友"/>
</LinearLayout>
PopupWindow的布局layout_more中包含2个Button
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/btn_add_by_contact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="通讯录"/>
<Button
android:id="@+id/btn_add_by_qq"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Q Q"/>
</LinearLayout>
让PopupWindow显示在Button上面
//popupwindow的布局
View popupView = View.inflate(PopupwindowActivity.this,R.layout.layout_more,null);
popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
//添加好友的按钮已经显示出来了,所以直接调用getHeight()即可拿到高度
int btnHeight = btn_add.getHeight();
//而弹出的view并没有显示出来,所以调用getMeasuredHeight()来得到高度
popupView.measure(0,0);
int viewHeight = popupView.getMeasuredHeight();
int yoff = btnHeight+viewHeight;
popupWindow.showAsDropDown(view,0,-yoff);
现在实现点击弹出的PopupWindow使其消失
if (popupWindow == null) {
//popupwindow的布局
final View popupView = View.inflate(PopupwindowActivity.this, R.layout.layout_more, null);
......
popupWindow.showAsDropDown(view, 0, -yoff);
Button btnAddContact = popupView.findViewById(R.id.btn_add_by_contact);
btnAddContact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
popupWindow.dismiss();
popupWindow = null;
}
});
}