android 三种弹出框之一PopupWindow

PopupWindow

  在android的弹出框我目前了解到的是有三种:AlertDialog,PopupWindow,Activity伪弹框,

  AlertDialog太熟悉了,这里就不介绍了

  就先看看PopupWindow

  API 给出的解释是:

  

  意思就是一个展示view的弹出窗体,这个弹出窗体将会浮动在当前activity的最上层,

  它和AlertDialog的区别是:
      1、AlertDialog的位置固定,而PopupWindow的位置可以随意;
      2、AlertDialog是非阻塞线程的,而PopupWindow是阻塞线程的

  下面就通过一个例子来说明PopupWindow的用法:

  Activity.class:

 1 public class MainActivity extends Activity {
 2 
 3     private Button btn;
 4 
 5     @Override
 6     protected void onCreate(Bundle savedInstanceState) {
 7         super.onCreate(savedInstanceState);
 8         setContentView(R.layout.activity_main);
 9         btn = (Button)findViewById(R.id.show);
10         btn.setOnClickListener(new Button.OnClickListener() {
11             
12             @Override
13             public void onClick(View v) {
14                 PopupWindow popupWindow = new PopupWindow(MainActivity.this);
15                 //这里是用在popupWindow中显示一个ListView, 你也可以加载一个xx.xml文件(Layoutfalter.from().inflate())
16                 ListView listView = new ListView(MainActivity.this);  
17                 ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_dropdown_item_1line, new String[]{"第一个" , "第二个"});
18                 listView.setAdapter(adapter);
19                 popupWindow.setContentView(listView);   //PopupWindow中要显示的view
20                 popupWindow.setHeight(500);
21                 popupWindow.setWidth(180);
22                 popupWindow.setOutsideTouchable(true);  //在PopupWindow范围外 默认为false
23                  popupWindow.setBackgroundDrawable(new ColorDrawable(Color.argb(50, 52, 53, 55)));
24                 /**
25                  * popupWindow.showAsDropDown(anchor, xoff, yoff)    用于标记Popupwindow要显示的在什么位置
26                  * anchor :至以那个view为标准位置
27                  * xoff :在 anchor为基准位置的x偏移量
28                  * yoff :在 anchor为基准位置的y偏移量
29                  */
30                 popupWindow.showAsDropDown(btn, 0, 0);
31                 
32             }
33         });
34         
35     }
36 
37     @Override
38     public boolean onCreateOptionsMenu(Menu menu) {
39         getMenuInflater().inflate(R.menu.main, menu);
40         return true;
41     }
42 
43 }

对应的xml文件就包含一个button就不贴出来了

源码下载:源码

 

 

三.用activity仿弹出框其实就直接在AndroidManifest.xml,对应要弹出的activity里面加个theme.例如:

1 <activity
2             android:name="com.example.activitypopup.PopupActivity"
3             android:label="这是一个Activity变成的Dialog"
4             android:theme="@android:style/Theme.Dialog" >
5  </activity>

 

 

posted @ 2014-05-13 00:29  perfect亮  阅读(2682)  评论(0编辑  收藏  举报