您的位置:首页 > 运维架构

<PopupWindow>的简单功能和用法

2016-06-05 14:27 281 查看
package com.crazyit.ui.popupwindowdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.PopupWindow;

/**
* PopupWindow 的简单功能和用法
*/
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//加载popup 对应的界面
View root = getLayoutInflater().inflate(R.layout.popup, null);

//创建 PopupWindow 对象
final PopupWindow popupWindow = new PopupWindow(root, 280, 360);

Button btn = (Button) findViewById(R.id.button);
if (btn != null) {
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//以下拉方式显示
popupWindow.showAsDropDown(v);  //方式1  显示在 popupwindow 的下方

//将 popupWindow显示在指定的位置
//  popupWindow.showAtLocation(findViewById(R.id.button), Gravity.CENTER, 40, 20);
}
});
}
root.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

//关闭 popupWindow
popupWindow.dismiss();
}
});
}
}


布局界面

<?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"
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.crazyit.ui.popupwindowdemo.MainActivity">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="弹出Popup窗口"
android:id="@+id/button"
/>
</RelativeLayout>


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"
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.crazyit.ui.popupwindowdemo.MainActivity">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="弹出Popup窗口"
android:id="@+id/button"
/>
</RelativeLayout>


使用popupWindow 创建对话框风格的窗口 需要以下2步

1. 调用 popupWindow的构造器创建PopupWindow对象

2. 调用 popupwindow的 showAsDropDown(View v) 将popupWindow作为v组件的下拉组件显示出来; 或者调用popupWindow 的showAtLocation() 方法将PopupWindow在指定的位置显示出来
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: