PopupWindow

簡單介紹下就是阻塞式的浮動窗口(類似dialog,但dialog為非阻塞式)

視窗下面的(退出、設置、取消)就是PopupWindow產生的頁面,其特點是跳出時,只會響應目前PopupWindow介面上的操作,其他並不會繼續進行直到執行dismiss()

MainActivity.java

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
public class MainActivity extends AppCompatActivity {
Button btn;
PopupWindow popupWindow;
View rootView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if (popupWindow == null)
{
showPopup();
} else {
popupWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
}
}
});
}
private void showPopup() {
// 載入popupwindow至view裡面
View view = LayoutInflater.from(this).inflate(R.layout.popupwindow_layout, null);
// 產生一個popupwindow的實例
popupWindow = new PopupWindow(this);
// 將view設定給新的popupwindow
popupWindow.setContentView(view);
// 設定popupwindow的高度和寬度
popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
// 取得主layout
rootView = LayoutInflater.from(this).inflate(R.layout.activity_main, null);
// 顯示popupwindow至主layout (顯示於底部)
popupWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
// 設定為false則不響應除了popupwindow以外的touch事件
popupWindow.setOutsideTouchable(false);
}
}
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
// popupwindow的layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_exit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_marginTop="2dp"
android:gravity="center_horizontal"
android:text="退出"
android:textStyle="bold" />
<TextView
android:id="@+id/tv_set"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_marginTop="2dp"
android:gravity="center_horizontal"
android:text="设置"
android:textStyle="bold" />
<TextView
android:id="@+id/tv_cancel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_marginTop="2dp"
android:gravity="center_horizontal"
android:text="取消"
android:textStyle="bold" />
</LinearLayout>

dialog為非阻塞式的窗口,也就是說執行dialog在start之後,下面的程式仍會繼續往下執行,並不會等到dialog被dismiss之後才執行,而popupwindow則會等到被dismiss之後才會繼續往下執行程式。

文章目錄
  1. 1. PopupWindow
    1. 1.1. PopupWindow 實作
      1. 1.1.1. MainActivity.java
      2. 1.1.2. popupwindow_layout.xml
|