1、设置显示的位置
// 一个参数
popupWindow.showAsDropDown(v);
//参数1: popupWindow关联的view
// 参数2和3:相对于关联控件的偏移量
popupWindow.showAsDropDown(View anchor, int xoff, int yoff)
2、是否会获取焦点
popupWindow.setFocusable(true);
3、设置背景
// popupWindow添加背景色
popupWindow.setBackgroundDrawable(ResourcesCompat.getDrawable(getResources(),R.drawable.img1,getTheme()));
4、关闭
popupWindow.dismiss();
5、设置加载动画
popupWindow.setAnimationStyle(R.anim.alpha); //设置动画
6、设置触摸使能和popupwindow外部的触摸使能
popupWindow.setTouchable(true);
popupWindow.setOutsideTouchable(true);
1、新建一个popupwindow要显示使用的xml文件popupview.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/mBtn1"
android:layout_width="100dp"
android:layout_height="50dp"
android:text="测试1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/mBtn2"
android:layout_width="100dp"
android:layout_height="50dp"
android:text="测试2"
android:layout_marginTop="10dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@id/mBtn1"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
2、在activity中使用:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tween_anim);
Button button=findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popupClick(v);
}
});
}
private void popupClick(View v) {
// 添加对应的view
View popupView = getLayoutInflater().inflate(R.layout.popup_view, null);
Button mBtn1=popupView.findViewById(R.id.mBtn1);
Button mBtn2=popupView.findViewById(R.id.mBtn2);
// ViewGroup.LayoutParams.WRAP_CONTENT: popupWindow包裹popupView
// 第四个参数为true,点击空白处popupWindow关闭
PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT,true);
// popupWindow添加背景色
popupWindow.setBackgroundDrawable(ResourcesCompat.getDrawable(getResources(),R.drawable.img1,getTheme()));
popupWindow.setAnimationStyle(R.anim.alpha); //设置动画
// popupWindow.showAsDropDown(v);
// 参数2和参数3是设置偏移量
popupWindow.showAsDropDown(v,popupView.getWidth(),-popupView.getHeight());
mBtn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
mBtn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
}