<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:gravity="center_horizontal" android:background="#B6A8D9"> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="240dp" android:src="@drawable/a" /> <Button android:id="@+id/close" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="关闭" /> </LinearLayout>
<LinearLayout 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:orientation="vertical" android:gravity="center_horizontal"> <Button android:id="@+id/bn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="弹出Popup窗口" /> </LinearLayout>
package com.example.popupwindow; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.PopupWindow; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //装载R.Layout.popup对应的界面布局 View root=this.getLayoutInflater().inflate(R.layout.popup, null); //创建PopupWindow对象 final PopupWindow popup=new PopupWindow(root,280,280); Button button=(Button) findViewById(R.id.bn); button.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { //下拉方式显示(按钮下方) popup.showAsDropDown(v); //设置指定位置 //popup.showAtLocation(findViewById(R.id.bn), Gravity.CENTER, 20, 20); } }); //获取PopupWindow中的关闭按钮 root.findViewById(R.id.close).setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { popup.dismiss(); } }); } }
时间: 2024-10-30 23:10:24