PopupWindow 可以創建類似於對話框風格的窗口,使用PopupWindow創建對話框只需兩個步驟
1)調用PopupWindow構造器創建PopupWindow對象
2)調用PopupWindow的showAsDropDown(View v)將PopupWindow作爲v的下拉顯示對象,或者調用PopupWindow的showAtLocation()來顯示PopupWindow的位置
以下爲一個簡單的代碼實例:
public class PopupWindowTest extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 裝載R.layout.popup對應的界面佈局
View root = this.getLayoutInflater().inflate(R.layout.popup, null);
// 創建PopupWindow對象
final PopupWindow popup = new PopupWindow(root, 280, 360);
Button button = (Button) findViewById(R.id.bn);
button.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// 以下拉方式顯示。
// popup.showAsDropDown(v);
//將PopupWindow顯示在指定位置
popup.showAtLocation(findViewById(R.id.bn), Gravity.CENTER, 20,
20);
}
});
// 獲取Popup窗口中的關閉按鈕。
root.findViewById(R.id.close).setOnClickListener(
new View.OnClickListener()
{
public void onClick(View v)
{
// 關閉Popup窗口
popup.dismiss();
}
});
}
}