A5下载 - 努力做内容最丰富最安全的下载站!

A5站长下载站

当前位置:A5下载 > 编程开发 > 安卓开发 > PopupWindow的使用

PopupWindow的使用

时间:2015-07-13 13:58作者:zhao人气:212

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);

}

}

});

}

}

最后显示的结果如图:

标签PopupWindow,使用,PopupWindow,组件

相关下载

查看所有评论+

网友评论

网友
您的评论需要经过审核才能显示

公众号