編輯:關於 Android 程式設計
在 Android 中,標題列的選項卡可使用 Dialog 或 PopupWindow 實作。相較於自訂 Dialog,PopupWindow 更輕量,適合顯示短暫選單或下拉式選項。
先將清單布局 inflate 出來,再設定 PopupWindow 的寬高、焦點與外部觸控行為:
popupWindow = new PopupWindow(MainActivity.this);
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.setWidth(getWindowManager().getDefaultDisplay().getWidth() / 2);
popupWindow.setHeight(300);
popupWindow.setOutsideTouchable(true);
popupWindow.setFocusable(true);
popupWindow.setContentView(layout);
可使用 showAtLocation 指定位置,並搭配 Gravity 控制對齊:
popupWindow.showAtLocation(findViewById(R.id.main),
Gravity.LEFT | Gravity.TOP, x, y);
若使用 showAsDropDown,則會以指定 View 作為參照,適合做為標題按鈕的下拉選單。
為 ListView 設定 OnItemClickListener,在使用者選擇項目後更新標題文字並關閉 PopupWindow:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView> parent, View view, int position, long id) {
button.setText(title[position]);
popupWindow.dismiss();
popupWindow = null;
}
});
實作時需特別注意 y 座標計算,若位置落在按鈕中央,可檢查 getBottom 與螢幕座標換算是否正確。
Android Studio 入門實用技巧整理
當初裝 Android Studio 只是為了看一份專案的原始碼——公司那時還在用 Eclipse 開發。沒想到用下來,Android Studio 真的相當好用。趁這幾
Android LayoutInflater 深入解析:inflate 三個參數的差異
常見誤解 許多開發者會以為 inflate(resource, null)、inflate(resource, root, false) 與 inflate(resour
Android 自動補全與滾動容器:AutoCompleteTextView 與 ScrollView 實務
AutoCompleteTextView 基本用法AutoCompleteTextView 會在使用者輸入時顯示建議清單。最簡單的方式是搭配 ArrayAdapter,並
Java 與 Android 回調機制詳解:從介面回調到異步通知
Java 與 Android 回調機制詳解 回調機制是程式中非常常見的設計手法。簡單來說,當 Client 呼叫 Service 的某個方法後,Service 在未來某個