編輯:關於 Android 程式設計
PopupWindow 的定位一直是新手最容易翻车的地方。經過幾輪嘗試,我總結出一套能讓它穩定彈出在目標控件正下方的寫法,這裡把完整代碼和幾個容易踩雷的細節一起記錄下來。
把 PopupWindow 繼承出來,在構造階段一次性處理佈局加載、寬高與焦點屬性,後續調用會乾淨很多。
package com.example.popwindowdemo;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.PopupWindow;
public class TestPopwindow2 extends PopupWindow {
// 根視圖
private View mRootView;
private LayoutInflater mInflater;
public TestPopwindow2(Activity context) {
super(context);
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRootView = mInflater.inflate(R.layout.test_popwindow_2, null);
setContentView(mRootView);
this.setWidth(LayoutParams.WRAP_CONTENT);
this.setHeight(LayoutParams.WRAP_CONTENT);
// 設置彈出相關屬性
setTouchable(true);
setOutsideTouchable(true);
setFocusable(true);
setBackgroundDrawable(new BitmapDrawable(context.getResources()));
update();
getContentView().setFocusableInTouchMode(true);
getContentView().setFocusable(true);
setAnimationStyle(R.style.AppBaseTheme);
}
}
這裡有兩點值得注意。setBackgroundDrawable() 一定要呼叫,傳入一個空的 BitmapDrawable 即可——少了這一句,點擊外部消失的行為會失效。setFocusable(true) 則保證彈窗能正確接收返回鍵。
package com.example.popwindowdemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener, OnDismissListener {
private TestPopwindow2 mTestPopwindow2 = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InitUI();
}
private void InitUI() {
mTestPopwindow2 = new TestPopwindow2(this);
// 點擊其他位置時讓彈窗消失
mTestPopwindow2.setOnDismissListener(this);
Button buttonTest2 = (Button) findViewById(R.id.buttonTest2);
buttonTest2.setOnClickListener(this);
}
private void OnPopwindowTest2() {
if (mTestPopwindow2 == null) return;
// 取得控件在屏幕上的位置
int[] location = new int[2];
View v = findViewById(R.id.buttonTest2);
if (v != null) v.getLocationOnScreen(location);
mTestPopwindow2.setAnimationStyle(R.style.AppBaseTheme);
// 讓彈窗出現在按鈕下方
mTestPopwindow2.showAtLocation(v, Gravity.TOP | Gravity.LEFT,
location[0] - v.getWidth(), location[1] + v.getHeight());
}
// 彈窗內部控件的點擊事件
public void OnclickTestListener(View view) {
switch (view.getId()) {
case R.id.layoutSeclect1:
Toast.makeText(this, "系統熱門方案", Toast.LENGTH_SHORT).show();
break;
case R.id.layoutSeclect2:
Toast.makeText(this, "個人熱門方案", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
if (mTestPopwindow2 != null) mTestPopwindow2.dismiss();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonTest2:
OnPopwindowTest2();
break;
default:
break;
}
}
@Override
public void onDismiss() {
}
}
定位的核心在 showAtLocation() 的四個參數:父容器、重力方向、x 偏移、y 偏移。這裡用 Gravity.TOP | Gravity.LEFT 搭配 location[0] - v.getWidth() 與 location[1] + v.getHeight(),就能讓彈窗左下角對齊按鈕正下方。
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout android:background="#0000"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="https://schemas.android.com/apk/res/android">
<!-- 注意:popupwindow 的佈局不要使用 layout_marginTop 這類屬性,
特別是在相對佈局中,整體靠左等設定都會影響定位 -->
<LinearLayout android:id="@+id/hot_layout"
android:background="@drawable/title_function_bg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout android:id="@+id/layoutSeclect1"
android:clickable="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="OnclickTestListener">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="系統熱門方案"
android:textColor="#fff"
android:textSize="18sp" />
</LinearLayout>
<LinearLayout android:id="@+id/layoutSeclect2"
android:clickable="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="OnclickTestListener">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="個人熱門方案"
android:textColor="#fff"
android:textSize="18sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
這段註解裡提到的限制很關鍵:PopupWindow 的佈局盡量不要依賴 margin 之類的定位屬性。一旦佈局整體偏移,後續靠 showAtLocation 做的位置計算就會失準,這是絕大多數「彈窗位置不對」問題的根源。
<LinearLayout android:id="@+id/LinearLayoutMain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools">
<LinearLayout android:gravity="right"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button android:id="@+id/buttonTest2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="測試2" />
</LinearLayout>
</LinearLayout>
運行結果如下:

整理成三條 checklist:一是別忘了 setBackgroundDrawable(),否則外部點擊關閉失效;二是彈窗佈局本身保持乾淨,不要摻入定位類屬性;三是定位計算交給 getLocationOnScreen() 加 showAtLocation() 的偏移參數,不要試圖靠佈局 margin 硬湊。
Android 底部彈出 PopupWindow 並讓背景漸變變暗
需求情境 在 Android 中,點擊按鈕後彈出選單是常見互動。PopupMenu 適合簡單選單,PopupWindow 則可自訂任意版面,更適合從底部彈出的操作面板。
Android SwipeRefreshLayout 下拉刷新源碼解析
本文通過實例梳理 SwipeRefreshLayout 的用法與源碼要點,供大家參考。 SwipeRefreshLayout 是 Google 在 support v4
Android 網路編程 UDP 實戰(三):搜索區域網內的所有設備
承接前面的 UDP 主題,本篇主要探討如何在區域網中搜索所有設備。這個需求在物聯網應用中相當常見,也頗具綜合性,因此特別將它放進標題。文末再補充一些網路編程的常見問題。
Android 自定義 ListView 的視差滾動效果
視差效果常見於首頁頭圖、引導頁與品牌頁面,其核心是讓不同層級的內容以不同速度移動,營造景深與動態感。本文以 ListView 為例,說明如何讓 HeaderView 在使