1 public class PopUpActivity extends Activity { 2 3 /** Called when the activity is first created. */ 4 5 @Override 6 7 public void onCreate(Bundle savedInstanceState) { 8 9 super.onCreate(savedInstanceState); 10 11 setContentView(R.layout.main); 12 13 LayoutInflater inflater = LayoutInflater.from(this); 14 15 // 引入窗口配置文件 16 17 View view = inflater.inflate(R.layout.main2, null); 18 19 // 创建PopupWindow对象 20 21 final PopupWindow pop = new PopupWindow(view, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false); 22 23 Button btn = (Button) findViewById(R.id.btn); 24 25 // 需要设置一下此参数,点击外边可消失 26 27 pop.setBackgroundDrawable(new BitmapDrawable()); 28 29 //设置点击窗口外边窗口消失 30 31 pop.setOutsideTouchable(true); 32 33 // 设置此参数获得焦点,否则无法点击 34 35 pop.setFocusable(true); 36 37 btn.setOnClickListener(new OnClickListener() { 38 39 40 41 @Override 42 43 public void onClick(View v) { 44 45 if(pop.isShowing()) { 46 47 // 隐藏窗口,如果设置了点击窗口外小时即不需要此方式隐藏 48 49 pop.dismiss(); 50 51 } else { 52 53 // 显示窗口 54 55 pop.showAsDropDown(v); 56 57 } 58 59 60 } 61 62 }); 63 64 } 65 66 }
main.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 3 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 4 5 android:layout_width="fill_parent" 6 7 android:layout_height="fill_parent" 8 9 android:orientation="vertical" > 10 11 12 <Button 13 14 android:id="@+id/btn" 15 16 android:layout_width="wrap_content" 17 18 android:layout_height="wrap_content" 19 20 android:text="dianji" /> 21 22 23 24 </LinearLayout>
main2.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/a" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="AAAAA" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="BBBBB" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="CCCCC" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="DDDDD" /> </LinearLayout>
转自:http://blog.csdn.net/android_xiaoqi/article/details/7618895