Android開發(fā)系列(二十六):使用PopupWindow創(chuàng)建對話框風(fēng)格的窗口
來源:程序員人生 發(fā)布時間:2014-11-05 08:03:43 閱讀次數(shù):2210次
創(chuàng)建對話框風(fēng)格的窗口很簡單,需要步驟:
1、調(diào)用PopupWindow的構(gòu)造器創(chuàng)建PopupWindow對象
2、調(diào)用PopupWindow的showAsDropDown(View v)作為v組件的下拉組件顯示出來:或調(diào)用PopupWindow的showAtLocation()方法將PopupWindow在指定位置顯示出來。
首先,我們創(chuàng)建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對話框風(fēng)格的窗口
然后,我們在主界面編輯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對應(yīng)的界面布局
View root = this.getLayoutInflater().inflate(R.layout.popup, null);
// 創(chuàng)建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中的關(guān)閉按鈕。
root.findViewById(R.id.close).setOnClickListener(
new View.OnClickListener()
{
public void onClick(View v)
{
// 關(guān)閉PopupWindow
popup.dismiss(); //負責(zé)燒毀、隱藏PopupWindow的關(guān)鍵代碼
}
});
}
}
我們還寫了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="關(guān)閉"
/>
</LinearLayout>
我們來看1下效果:

生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機掃描二維碼進行捐贈