9. PopupWindow
9. PopupWindow
9.1 常用方法
方法 含义
setContentView 设置PopupWindow显示的View
showAsDropDown(View anchor) 相对某个控件的位置(正左下方),无偏移
showAsDropDown(View anchor,int xoff , int yoff) 相对某个控件的位置,有偏移
setFocusable 设置是否获取焦点
setBackgroundDrawable 设置背景
dismiss 关闭弹窗
setAnimationStyle 设置加载动画
setTouchable 设置触摸使能
setOutsideTouchable 设置PopupWindow外面的触摸使能
9.2 演示
<?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:orientation="vertical"
>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="弹出PopupWindow"
/>
</LinearLayout>
popup_view.xml
<?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:orientation="vertical"
android:background="@mipmap/ic_launcher"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn1"
android:padding="5dp"
android:text="上海"
android:textSize="18sp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn2"
android:padding="5dp"
android:text="北京"
android:textSize="18sp"
/>
</LinearLayout>
Button btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
View popupView = getLayoutInflater().inflate(R.layout.popup_view,null);
PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
popupWindow.showAsDropDown(view); //显示在按钮下方
}
});
有偏移的popupwindow
这个时候点击空白处,window不会消失
→ 设置可获取焦点
这下点击空白处,就会关闭window了
设置背景
设置popupwindow中按钮的监听事件
Button btn1 = popupView.findViewById(R.id.btn1);
Button btn2 = popupView.findViewById(R.id.btn2);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
System.out.println("上海");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
System.out.println("北京");
}
});
点击后设置关闭弹窗
dismiss()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现