activity_popup_window_test.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"
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=".PopupWindowTest" >
<Button
android:id="@+id/bn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="弹出窗口"
/>
</RelativeLayout>
popup.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"
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=".PopupWindowTest" >
<TextView
android:id="@+id/popup_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="我是弹出窗口"
/>
<Button
android:id="@+id/close"
android:layout_below="@id/popup_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="关闭"
/>
</RelativeLayout>
PopupWindowTest.java
package com.example.popupwindowtest;
import android.os.Bundle;
import android.app.Activity;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupWindow;
public class PopupWindowTest extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_popup_window_test);
//装载R.layout.popup对应的界面布局
View root = this.getLayoutInflater().inflate(R.layout.popup, null);
//创建PopupWindow对象
final PopupWindow popup = new PopupWindow(root,280,360);
Button button = (Button) findViewById(R.id.bn);
button.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//以下拉方式显示
//popup.showAsDropDown(v);
//将Popupwindow显示在指定位置
popup.showAtLocation(findViewById(R.id.bn), Gravity.CENTER, 20, 20);
}
});
root.findViewById(R.id.close).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
popup.dismiss();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.popup_window_test, menu);
return true;
}
}