前言
PopupWindow与AlertDialog的区别
最关键的区别是AlertDialog不能指定显示位置,只能默认显示在屏幕最中间(当然也可以通过设置WindowManager参数来改变位置)。而PopupWindow是可以指定显示位置的,随便哪个位置都可以,更加灵活。
一、使用PopupWindow
1.1、PopupWindow布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/ic_launcher"
android:orientation="vertical">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="上海"
android:textSize="18sp" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="北京"
android:textSize="18sp" />
</LinearLayout>
1.2、MainActivity
package com.enjoy.mypopupwindow;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void leoClick(View view) {
//设置popupwindow的布局
View popupView = getLayoutInflater().inflate(R.layout.popup_view, null);
//获取popupwindow的布局中的按钮
View btn1 = popupView.findViewById(R.id.btn1);
View btn2 = popupView.findViewById(R.id.btn2);
PopupWindow popupWindow = new PopupWindow(popupView,ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,true); //true表示失去焦点,就退出popupwindow
//设置背景
popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.ceshi));
popupWindow.showAsDropDown(view); //可以设置偏移量
//给popupwindow的布局中的按钮绑定事件
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("zzuli","OnClike:上海");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("zzuli","OnClike:北京");
popupWindow.dismiss(); //退出
}
});
}
}