Android開發系列(二十六):使用PopupWindow創建對話框風格的窗口
來源:程序員人生 發布時間:2014-11-05 08:03:43 閱讀次數:2213次
創建對話框風格的窗口很簡單,需要步驟:
1、調用PopupWindow的構造器創建PopupWindow對象
2、調用PopupWindow的showAsDropDown(View v)作為v組件的下拉組件顯示出來:或調用PopupWindow的showAtLocation()方法將PopupWindow在指定位置顯示出來。
首先,我們創建1個Android項目,然后編輯main.xml文件:
<?xml version="1.0" encoding="utf⑻"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal">
<Button android:id="@+id/bn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="彈出Popup窗口"
/>
</LinearLayout>
我們定義了1個按鈕,用來打開Popup對話框風格的窗口
然后,我們在主界面編輯java代碼:PopupWindowTest.java
import android.app.Activity;
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;
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);
}
});
// 獲得PopupWindow中的關閉按鈕。
root.findViewById(R.id.close).setOnClickListener(
new View.OnClickListener()
{
public void onClick(View v)
{
// 關閉PopupWindow
popup.dismiss(); //負責燒毀、隱藏PopupWindow的關鍵代碼
}
});
}
}
我們還寫了1個PopupWindow對話框的xml文件:popup.xml
<?xml version="1.0" encoding="utf⑻"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
android:background="#B1C9E4"
>
<ImageView
android:layout_width="240dp"
android:layout_height="wrap_content"
android:src="@drawable/java"
/>
<Button
android:id="@+id/close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="關閉"
/>
</LinearLayout>
我們來看1下效果:

生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈