主布局
<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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.popupwindow.MainActivity" android:id="@+id/main" > <!-- 注意这里要设置布局文件的id为main,后面要调用到 --> <!-- 定义按钮和点击事件 --> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="135dp" android:text="打开PopupWindow" android:onClick="openPopupWindow" /> </RelativeLayout>
Popup对话框布局
<?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="@drawable/aa" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="这是PopupWindow" android:textSize="30dp" android:textColor="#823627"/> </LinearLayout>
package com.example.popupwindow; import android.app.Activity; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.PopupWindow; public class MainActivity extends Activity { private PopupWindow popupWindow; private View parent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /* * 得到布局填充符getLayoutInflater(),也可通过系统服务getSystemService(name)得到 * inflate指定布局文件的id */ View contentView = getLayoutInflater().inflate(R.layout.popup_window, null); /* * 第一个参数:PopupWindow要显示的界面 * 第二个参数:PopupWindow的宽 * 第三个参数:PopupWindow的高 */ popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); popupWindow.setFocusable(true); //让小窗口取得焦点,不然怎么点也不会有反应 popupWindow.setBackgroundDrawable(new BitmapDrawable()); //点空白处关掉Popup窗口,在背景new一个位图对象就可以了 parent = this.findViewById(R.id.main); //以上main为当前Activity对应的布局文件 } public void openPopupWindow(View v){ //显示PopupWindow的方法要多个,可设置具体显示位置方式 popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0); } }
运行结果
点击按钮
时间: 2024-10-11 07:17:05