示例效果如下:
mainactivity.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
package sn.qdj.popupwindowdemo; import android.support.v7.app.actionbaractivity; import android.os.bundle; import android.view.gravity; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.popupwindow; /** * popupwindow使用 * @author qingdujun * */ public class mainactivity extends actionbaractivity { @override protected void oncreate(bundle savedinstancestate) { super .oncreate(savedinstancestate); setcontentview(r.layout.activity_main); /** * popup.xml 为弹出界面布局 */ view root = getlayoutinflater().inflate(r.layout.popup, null ); /** * 弹出界面 * 宽度:400 * 高度:200 */ final popupwindow popup = new popupwindow(root, 400 , 200 ); button btn = (button)findviewbyid(r.id.btn); button close = (button)findviewbyid(r.id.close); btn.setonclicklistener( new onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub /** * 在指定位置弹出 * * 第一个参数指定popupwindow的锚点view,即依附在哪个view上。 * 第二个参数指定起始点为parent的右下角 * 第三个参数设置以btn的下方为原点,向左、上各偏移0像素。 */ popup.showatlocation(findviewbyid(r.id.btn), gravity.bottom, 0 , 0 ); } }); close.setonclicklistener( new onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub /** * 关闭popupwindow */ popup.dismiss(); } }); } } |
activity_main.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<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" > <button android:id= "@+id/btn" android:layout_width= "200dp" android:layout_height= "wrap_content" android:layout_alignparenttop= "true" android:text= "弹出" /> <button android:id= "@+id/close" android:layout_width= "200dp" android:layout_height= "wrap_content" android:layout_torightof= "@id/btn" android:text= "关闭" /> </relativelayout> |
popup.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<?xml version= "1.0" encoding= "utf-8" ?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "match_parent" android:layout_height= "match_parent" android:orientation= "vertical" > <button android:id= "@+id/btn1" android:layout_width= "match_parent" android:layout_height= "wrap_content" android:text= "相册" /> <button android:id= "@+id/btn2" android:layout_width= "match_parent" android:layout_height= "wrap_content" android:text= "拍照" /> </linearlayout> |