public class PopUpActivity extends Activity { |
02 | /** Called when the activity is first created. */ |
03 | @Override |
04 | public void onCreate(Bundle savedInstanceState) { |
05 | super .onCreate(savedInstanceState); |
06 | setContentView(R.layout.main); |
07 | LayoutInflater inflater = LayoutInflater.from( this ); |
08 | // 引入窗口配置文件 |
09 | View view = inflater.inflate(R.layout.main2, null ); |
10 | // 创建PopupWindow对象 |
11 | final PopupWindow pop = new PopupWindow(view, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false ); |
12 | Button btn = (Button) findViewById(R.id.btn); |
13 | // 需要设置一下此参数,点击外边可消失 |
14 | pop.setBackgroundDrawable( new BitmapDrawable()); |
15 | //设置点击窗口外边窗口消失 |
16 | pop.setOutsideTouchable( true ); |
17 | // 设置此参数获得焦点,否则无法点击 |
18 | pop.setFocusable( true ); |
19 | btn.setOnClickListener( new OnClickListener() { |
20 | |
21 | @Override |
22 | public void onClick(View v) { |
23 | if (pop.isShowing()) { |
24 | // 隐藏窗口,如果设置了点击窗口外小时即不需要此方式隐藏 |
25 | pop.dismiss(); |
26 | } else { |
27 | // 显示窗口 |
28 | pop.showAsDropDown(v); |
29 | } |
30 | |
31 | } |
32 | }); |
33 | } |
34 | } |
main.xml
01 | <? xml version = "1.0" encoding = "utf-8" ?> |
02 | < LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" |
03 | android:layout_width = "fill_parent" |
04 | android:layout_height = "fill_parent" |
05 | android:orientation = "vertical" > |
06 | |
07 | < Button |
08 | android:id = "@+id/btn" |
09 | android:layout_width = "wrap_content" |
10 | android:layout_height = "wrap_content" |
11 | android:text = "dianji" /> |
12 | |
13 | </ LinearLayout > |
01 | <? xml version = "1.0" encoding = "utf-8" ?> |
02 | < LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" |
03 | android:layout_width = "fill_parent" |
04 | android:layout_height = "fill_parent" |
05 | android:orientation = "vertical" > |
06 | |
07 | < Button |
08 | android:id = "@+id/a" |
09 | android:layout_width = "wrap_content" |
10 | android:layout_height = "wrap_content" |
11 | android:text = "AAAAA" /> |
12 | |
13 | < Button |
14 | android:layout_width = "wrap_content" |
15 | android:layout_height = "wrap_content" |
16 | android:text = "BBBBB" /> |
17 | |
18 | < Button |
19 | android:layout_width = "wrap_content" |
20 | android:layout_height = "wrap_content" |
21 | android:text = "CCCCC" /> |
22 | |
23 | < Button |
24 | android:layout_width = "wrap_content" |
25 | android:layout_height = "wrap_content" |
26 | android:text = "DDDDD" /> |
27 | |
28 | </ LinearLayout > |