它是浮在别的窗口之上的.
下面我将给大家做一个简单的Demo,类似于音乐播放器的Widget的效果,点击Button的时候出来PopupWindow,首先我们看一下效果图:
1. package com.android.tutor;
2. import android.app.Activity;
3. import android.content.Context;
4. import android.os.Bundle;
5. import android.view.Gravity;
6. import android.view.LayoutInflater;
7. import android.view.View;
8. import android.view.View.OnClickListener;
9. import android.view.ViewGroup.LayoutParams;
10. import android.widget.Button;
11. import android.widget.PopupWindow;
12. public class PopupWindowDemo extends Activity implements OnClickListener{
13. private Button btn;
14.
15. public void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.main);
18.
19. btn = (Button)findViewById(R.id.btn);
20. this);
21. }
22. @Override
23. public void onClick(View v) {
24. this;
25. if (v.getId() == R.id.btn) {
26. LayoutInflater mLayoutInflater = (LayoutInflater) mContext
27. .getSystemService(LAYOUT_INFLATER_SERVICE);
28. View music_popunwindwow = mLayoutInflater.inflate(
29. null);
30. new PopupWindow(music_popunwindwow, LayoutParams.FILL_PARENT,
31. LayoutParams.WRAP_CONTENT);
32.
33. 0, 0);
34. }
35. }
36. }
要强调的是这里PopupWindow必须有某个事件触发才会显示出来,不然总会抱错,不信大家可以试试!
随着这个问题的出现,就会同学问了,那么我想初始化让PopupWindow显示出来,那怎么办了,不去寄托于其他点击事件,
在这里我用了定时器Timer来实现这样的效果,当然这里就要用到Handler了,如果大家不理解的可以返回
1. package com.android.tutor;
2. import java.util.Timer;
3. import java.util.TimerTask;
4. import android.app.Activity;
5. import android.content.Context;
6. import android.os.Bundle;
7. import android.os.Handler;
8. import android.os.Message;
9. import android.view.Gravity;
10. import android.view.LayoutInflater;
11. import android.view.View;
12. import android.view.ViewGroup.LayoutParams;
13. import android.widget.PopupWindow;
14. public class PopupWindowDemo extends Activity{
15. private Handler mHandler = new Handler(){
16.
17. public void handleMessage(Message msg) {
18. switch (msg.what) {
19. case 1:
20. showPopupWindow();
21. break;
22. }
23. };
24. };
25.
26. public void onCreate(Bundle savedInstanceState) {
27. super.onCreate(savedInstanceState);
28. setContentView(R.layout.main);
29.
30. //create the timer
31. new Timer();
32. new initPopupWindow(), 100);
33. }
34.
35. private class initPopupWindow extends TimerTask{
36. @Override
37. public void run() {
38.
39. new Message();
40. 1;
41. mHandler.sendMessage(message);
42.
43. }
44. }
45.
46.
47. public void showPopupWindow() {
48. this;
49. LayoutInflater mLayoutInflater = (LayoutInflater) mContext
50. .getSystemService(LAYOUT_INFLATER_SERVICE);
51. View music_popunwindwow = mLayoutInflater.inflate(
52. null);
53. new PopupWindow(music_popunwindwow,
54. LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
55. 0, 0);
56. }
57. }
58.