編輯:關於 Android 開發
在實際開發中,LayoutInflater 是個相當實用的類別。它的作用有點類似 findViewById(),但兩者分工不同:LayoutInflater 找的是 layout 下的 XML 版面檔並將其實例化,而 findViewById() 找的是某個 XML 裡的具體 widget 控制項(如 Button、TextView)。一句話概括:LayoutInflater 負責把 XML 變成 View 物件樹,findViewById 負責在已有的 View 樹裡撈出特定節點。
下面做一個簡單的 Demo:主版面 main.xml 裡有一個 TextView 和一個 Button;點擊 Button 後彈出一個 Dialog,而這個 Dialog 的版面用的是我們自己在 layout 目錄下定義的 custom_dialog.xml(左右分布,左邊 ImageView、右邊 TextView)。
1. 新建一個Android專案,命名為 LayoutInflaterDemo。
2. 修改 main.xml,在原本的 TextView 之外加上一個 Button:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ShowCustomDialog"
/>
</LinearLayout>
3. 在 Button 的點擊事件裡,透過 LayoutInflater.from(this).inflate(R.layout.custom_dialog, null) 取得 custom_dialog 的 View,再把它設為 Dialog 的內容檢視即可。
inflate 的第二個參數不要習慣性寫 null 以外的東西而不思考。inflate(resource, root) 中的 root 決定要不要把生成的 View 掛到父容器上、以及版面參數(LayoutParams)由誰決定。建立 Dialog 內容時 root 通常傳 null,因為 Dialog 會自己接管;但若是要把一塊 View 動態插入既有的 LinearLayout,就該傳入該容器並讓 attachToRoot 為 true,否則 LayoutParams 會全部失效,寬高變成預設值。
LayoutInflater 了三個取得方式。LayoutInflater.from(context) 最常用;Activity 本身也有 getLayoutInflater();系統另有 Context.getSystemService(LAYOUT_INFLATER_SERVICE)。三者本質相同,挑順手的即可。
JNI 呼叫 OpenCV 與直接使用 Android 版 OpenCV:圖片效果轉換實作對照
JNI 呼叫 OpenCV 與直接使用 Android 版 OpenCV:圖片效果轉換實作對照 先看幾張實際跑出來的效果圖。如果程式執行時提示需要安裝某某 Manager
使用第三方開源框架 PullToRefreshListView 實作下拉刷新列表
使用第三方開源框架 PullToRefreshListView 實作下拉刷新列表 PullToRefreshListView 是一款廣受歡迎的第三方開源自下而上刷新列表元
以 Adapter 模式重構 Android 圓形菜單
以 Adapter 模式重構 Android 圓形菜單 圓形菜單這類自訂 UI 很能吸引注意,但真正可維護的關鍵,在於如何隔離變化。本文以重構圓形菜單為例,說明如何透過
Android SQLite 數據庫開發筆記
Android SQLite 數據庫開發筆記 SQLite 是 Android 內建的輕量級關聯式數據庫,適合用來保存結構化資料。開發時通常會建立 SQLiteOpenH