分类分类
更新时间:2026-03-29 00:32:44作者:zhao
PopupWindow组件的使用类似于alertDialog,我们先来看看官网对于PopupWindow组件的描述是什么样子的:
A popup window that can be used to display an arbitrary view. The popup window is a floating container that appears on top of the current activity.
PopupWindow可以用来显示任意的视图。PopupWindow是一个浮动的容器用来装载其他组件并且显示在当前activity的最上层。
说明比较简单,那么我们先来使用一个小demo显示一下PopupWindow组件
首先是我们的布局文件,就是简单的添加了一个button组件,layout.xml
<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=".Main" >
<Button android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="40dip"
android:text="click me!"/>
</RelativeLayout>
我们要使用一个pop.xml,在其中添加一个ImageView用于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:layout_width="128dip" android:layout_height="128dip" android:background="@drawable/bluefat" />
</LinearLayout>
最后是我们的主代码:
package com.example.android_popupview1;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;
public class Main extends Activity {
Button btn = null;
PopupWindow pwindow = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//初始化button
btn = (Button) this.findViewById(R.id.btn);
LayoutInflater inflater = this.getLayoutInflater();
//生成一个view以便popupWindow填充
View view = inflater.inflate(R.layout.pop, null);
//构造popupwindow
pwindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, true);
//点击出现的图片时,popupwindow消失
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
pwindow.dismiss();
}
});
//点击按钮的时候出现popupwindow
btn.setOnClickListener(new OnClickListener() {
@SuppressLint("NewApi")
@Override
public void onClick(View v) {
if (!pwindow.isShowing()) {
pwindow.showAtLocation(v, Gravity.CENTER, 0,0);
pwindow.setFocusable(true);
}
}
});
}
}
最后显示的结果如图:
相关
王道三国策略游戏380.18 MBv0.0.12026-03-28
下载刮个爽手机版休闲益智186.96 MBv1.0.282026-03-28
下载龙符天祭策略游戏756.03 Mv22026-03-28
下载入魂一番赏app网上购物106.66 Mv4.3.52026-03-28
下载童话师经营养成504.02 Mv1.1.52026-03-28
下载Bebo Cam app图像拍照264.51 Mv2.3.02026-03-28
下载纯三国官方正版策略游戏167.24 Mv0.0.12026-03-28
下载Poka Cam app图像拍照74.7 Mv1.8.02026-03-28
下载COLMO app趣味娱乐199.15 Mv2.3.5.22026-03-28
下载愤怒的小鸟变形金刚苹果版休闲游戏439.4 Mv2.39.02026-03-28
下载这也能切苹果版休闲游戏479.6 Mv21342026-03-28
下载口袋吉伊卡哇苹果手机版模拟游戏920.4 Mv2.0.02026-03-28
下载










