Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android PopupWindow 彈出視窗的使用示範

編輯:關於 Android 程式設計

PopupWindow 是一個可浮動在任何檢視之上的輕量容器,常用來做「點選後出現相簿/拍照」這類浮動選單,比 Dialog 更不會遮斷使用者操作。

執行效果

MainActivity

先 inflate 彈出內容的版面,用它建立 PopupWindow 物件,觸發時呼叫 showAtLocation(),關閉時呼叫 dismiss()。

 package sn.qdj.popupwindowdemo;

import android.support.v7.app.ActionBarActivity;
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;

/**
* PopupWindow 使用
* @author qingdujun
*/
public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

/**
* popup.xml 為彈出界面布局
*/
View root = getLayoutInflater().inflate(R.layout.popup, null);

/**
* 彈出界面
* 寬度:400
* 高度:200
*/
final PopupWindow popup = new PopupWindow(root, 400, 200);

Button btn = (Button)findViewById(R.id.btn);
Button close = (Button)findViewById(R.id.close);

btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
/**
* 在指定位置彈出
*
* 第一個參數指定 PopupWindow 的錨點 view,即依附在哪個 view 上。
* 第二個參數指定起始點為 parent 的右下角
* 第三個參數設置以 btn 的下方為原點,向左、上各偏移 0 像素。
*/
popup.showAtLocation(findViewById(R.id.btn), Gravity.BOTTOM, 0, 0);
}
});

close.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
/**
* 關閉 PopupWindow
*/
popup.dismiss();
}
});
}
}

activity_main.xml

 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
android:id="@+id/btn"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="彈出" />

<Button
android:id="@+id/close"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/btn"
android:text="關閉" />

</RelativeLayout>

popup.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="相冊" />

<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="拍照" />

</LinearLayout>

三個實務建議

第一,顯示時加上 setOutsideTouchable(true) 與 setFocusable(true),點擊外部才能自動關閉。第二,若要更精準地貼齊某個檢視,改用 showAsDropDown(anchorView, x, y) 會比 showAtLocation() 方便,它會自動依錨點位置計算座標並處理鍵盤遮擋。第三,若只是想顯示一個選單清單,直接考慮 ListPopupWindow 或 PopupMenu,能省下自己寫 Adapter 的功夫。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved