Android開發系列(二十六):使用PopupWindow建立對話方塊風格的視窗

來源:互聯網
上載者:User

標籤:對話方塊   介面   

建立對話方塊風格的視窗很簡單,需要步驟:

1、調用PopupWindow的構造器建立PopupWindow對象

2、調用PopupWindow的showAsDropDown(View v)作為v組件的下拉組件顯示出來:或調用PopupWindow的showAtLocation()方法將PopupWindow在指定位置顯示出來。


首先,我們建立一個Android項目,然後編輯main.xml檔案:

<?xml version="1.0" encoding="utf-8"?><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>
我們定義了一個按鈕,用來開啟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{@Overridepublic 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(){@Overridepublic 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){// 關閉PopupWindowpopup.dismiss(); //負責銷毀、隱藏PopupWindow的關鍵代碼}});}}


我們還寫了一個PopupWindow對話方塊的xml檔案:popup.xml

<?xml version="1.0" encoding="utf-8"?><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"/><Buttonandroid:id="@+id/close"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="關閉" /></LinearLayout>



我們來看一下效果:






Android開發系列(二十六):使用PopupWindow建立對話方塊風格的視窗

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.