PopWindow是一个弹出的窗口,它的效果就是在当前Activity上面再显示一层图层。
这是它的继承关系:
java.lang.Object
↳ android.widget.PopupWindow
他的实现方式有多种,比如我们可以用PopupWindow(Context context) 和
PopupWindow() 实现。
本文主要描述的是类似效果的实现:
初始化方法:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
parentView = getLayoutInflater().inflate(R.layout.activity_basic_infor, null);
setContentView(parentView);
initPopWindow();
}
public void initPopWindow() {
pop = new PopupWindow(BasicInforActivity.this);//获得PopupWindow对象
View view = getLayoutInflater().inflate(R.layout.layout_popupwindows, null);//加载PopupWindow的布局
ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
pop.setWidth(LayoutParams.MATCH_PARENT);//设置宽度高度
pop.setHeight(LayoutParams.WRAP_CONTENT);
pop.setBackgroundDrawable(new BitmapDrawable());
pop.setFocusable(true);//设置是否获得焦点
pop.setOutsideTouchable(true);//设置当点击外部时的效果
pop.setContentView(view);//将布局加载到pop中
RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);//获取界面中的各种控件
Button btnTakePhoto = (Button) view.findViewById(R.id.item_popupwindows_camera);
Button btnAblum = (Button) view.findViewById(R.id.item_popupwindows_Photo);
Button btnCancle = (Button) view.findViewById(R.id.item_popupwindows_cancel);
parent.setOnClickListener(this);//Activity实现OnClickListner,设置监听。
btnTakePhoto.setOnClickListener(this);
btnAblum.setOnClickListener(this);
btnCancle.setOnClickListener(this);
}
布局文件代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/parent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#99000000" >
<LinearLayout
android:id="@+id/ll_popup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:orientation="vertical" >
<Button
android:id="@+id/item_popupwindows_camera"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#ffffff"
android:text="拍照"
android:textSize="15sp" />
<View
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:background="#f3f3f3" />
<Button
android:id="@+id/item_popupwindows_Photo"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#ffffff"
android:text="从相册中选取"
android:textSize="15sp" />
<Button
android:id="@+id/item_popupwindows_cancel"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginBottom="15dp"
android:layout_marginTop="15dp"
android:background="#ffffff"
android:text="取消" />
</LinearLayout>
</RelativeLayout>
最后就是显示PopupWindow和隐藏的代码:
pop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);//显示的代码
pop.dismiss();//消失的代码
ll_popup.clearAnimation();