【Android - 进阶】之PopupWindow的使用
2024-09-01 17:26:36
创建一个类继承自PopupWindow,编写自定义的PopupWindow类。示例代码如下:
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow; /**
* 自定义的PopupWindow
*/
public class MyPopWindow extends PopupWindow { public MyPopWindow(Activity context) {
// 通过layout的id找到布局View
View contentView = LayoutInflater.from(context).inflate(R.layout.pop_custom, null);
// 获取PopupWindow的宽高
int h = context.getWindowManager().getDefaultDisplay().getHeight();
int w = context.getWindowManager().getDefaultDisplay().getWidth();
// 设置PopupWindow的View
this.setContentView(contentView);
// 设置PopupWindow弹出窗体的宽高
this.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
// 设置PopupWindow弹出窗体可点击(下面两行代码必须同时出现)
this.setFocusable(true);
this.setOutsideTouchable(true); // 当点击外围的时候隐藏PopupWindow
// 刷新状态
this.update();
// 设置PopupWindow的背景颜色为半透明的黑色
ColorDrawable dw = new ColorDrawable(Color.parseColor("#66000000"));
this.setBackgroundDrawable(dw);
// 设置PopupWindow弹出窗体动画效果
this.setAnimationStyle(R.style.PopWindowAnimStyle); // 这里也可以从contentView中获取到控件,并为它们绑定控件
} // 显示PopupWindow,有两种方法:showAsDropDown、showAtLocation
public void showPopupWindow(View parent) {
if (!this.isShowing()) {
// showAsDropDown方法,在parent下方的(x,y)位置显示,x、y是第二和第三个参数
// this.showAsDropDown(parent, parent.getWidth() / 2 - 400, 18); // showAtLocation方法,在parent的某个位置参数,具体哪个位置由后三个参数决定
this.showAtLocation(parent, Gravity.CENTER, 0, 0);
} else {
this.dismiss();
}
}
}
调用代码:
MyPopWindow popWindow = new MyPopWindow(MainActivity.this);
popWindow.showPopupWindow(new View(MainActivity.this));
最新文章
- Java中Vector和ArrayList的区别
- javascript操控浏览器
- 使用MiniProfiler给Asp.net MVC和Entity Framework号脉(附源码)
- php代码优化,mysql语句优化,面试需要用到的
- python (7)读取整个目录的所有文件夹并存入
- Unity协程(Coroutine)原理深入剖析(转载)
- jquery实现抽奖转盘
- sharepoint 2010 页面添加footer方法 custom footer for sharepoint 2010 master page
- Servlet一些基础
- iOS UIWebView 加载进度条的使用-WKWebView的使用,更新2017.6.26
- width和max-width的用处
- CF-551-D-树dp/思维
- Verilog编码规范与时序收敛
- var_export 掉咋天
- Android下利用zxing类库实现扫一扫
- C# Monitor实现
- Ex 5_21 无向图G=(V,E)的反馈边集..._第九次作业
- Beta冲刺阶段5.0
- The way to Go(1): Introduction
- 1-0 superset的安装和配置