UI组件之PopupWindow

来源:互联网 发布:中国房地产统计数据库 编辑:程序博客网 时间:2024/05/20 09:47

UI组件之PopupWindow

PopupWindow简介

PopupWindow也是对话框的一种,它和AlertDialog的不同之处就是AlertDialog的位置是固定的,而PopupWindow的位置是可以任意设置的

PopupWindow的创建

PopupWindow  popupWindow = new PopupWindow(参数1, 参数2, 参数3);

参数1:PopupWindow的内容,也就是PopupWindow的布局
参数2:PopupWindow的宽
参数3:PopupWindow的高

创建一个PopupWindow

主界面布局代码

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">    <Button        android:id="@+id/button"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="弹出一个Popup窗口" /></RelativeLayout>

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:orientation="vertical"    >    <ImageView        android:src="@drawable/baby0"        android:layout_width="400dp"        android:layout_height="400dp" />    <Button        android:id="@+id/btn_close"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="关闭"        /></LinearLayout>

Activity代码

package com.shake.day11_android_5;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.Gravity;import android.view.LayoutInflater;import android.view.View;import android.view.WindowManager;import android.widget.PopupWindow;public class MainActivity extends AppCompatActivity implements View.OnClickListener {    private PopupWindow popupWindow;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        findViewById(R.id.button).setOnClickListener(this);        //装载PopupWindow的布局        View popup_view = LayoutInflater.from(this).inflate(R.layout.popup_layout, null);        //创建PopupWindow对象,PopupWindow的宽度和屏幕宽度一样        popupWindow = new PopupWindow(popup_view, WindowManager.LayoutParams.MATCH_PARENT, 1500);        //设置动画属性        popupWindow.setAnimationStyle(android.R.style.Animation_Translucent);        //关闭PopupWindow的按钮监听事件        popup_view.findViewById(R.id.btn_close).setOnClickListener(this);    }    @Override    public void onClick(View v) {        switch (v.getId()) {            case R.id.button:                //以下拉方式显示                popupWindow.showAsDropDown(v);                break;            case R.id.btn_close:                //关闭PopupWindow                popupWindow.dismiss();                break;        }    }}

效果
这里写图片描述

点击了弹出按钮之后,再点击关闭按钮PopupWindow就会消失
这里写图片描述

0 0
原创粉丝点击