編輯:關於 Android 程式設計
findViewById 大概是 Android 開發中用得最多的方法之一,但它有一個讓人頭疼的地方:返回值永遠是 View,每次使用都要手動做一次強制類型轉換。代碼醜陋不說,一旦轉錯類型,還會在運行時拋出 ClassCastException,而編譯期完全無法察覺。
典型的 Activity 初始化代碼是這樣的:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 查找子控件
TextView textView = (TextView) findViewById(R.id.my_textview);
ImageView imageView = (ImageView) findViewById(R.id.my_imageview);
ListView listView = (ListView) findViewById(R.id.my_listview);
}
頁面控件一多,這種代碼就會迅速膨脹成幾十行單調的轉換語句。每個人都寫過,每個人都覺得噁心。
Java 的泛型方法允許在調用時由「接收方的類型」自動推導返回類型,這正好是我們需要的。封裝一個 ViewFinder 工具類:
使用方式變成:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化
ViewFinder.initContentView(this, R.layout.activity_main);
// 查找子控件,无需强制转换
TextView textView = ViewFinder.findViewById(R.id.my_textview);
ImageView imageView = ViewFinder.findViewById(R.id.my_imageview);
ListView listView = ViewFinder.findViewById(R.id.my_listview);
}
編寫器會根據左側變量的聲明類型自動推斷 T,返回值直接就是 TextView、ImageView、ListView。類型不匹配時,錯誤會在編譯階段就暴露,而不是等到運行時才崩潰。
/**
* 便於在單個佈局中查找子 View 的工具類。
* findViewById 為泛型方法,返回的 view 直接就是接收方的類型,
* 無需進行強制類型轉換。
*
* 使用示例:
* ViewFinder.initContentView(context, R.layout.activity_main);
* TextView textView = ViewFinder.findViewById(R.id.my_textview);
*
* @author mrsimple
*/
public final class ViewFinder {
/** LayoutInflater */
static LayoutInflater mInflater;
/** 已查找過的子 View 緩存,key 為 view id */
private static SparseArray<View> mViewMap = new SparseArray<View>();
/** 根視圖 */
static View mContentView;
/**
* 初始化 ViewFinder,本質上是加載並持有該頁面的 ContentView。
*
* @param context 上下文
* @param layoutId 佈局資源 id
*/
public static void initContentView(Context context, int layoutId) {
mInflater = LayoutInflater.from(context);
mContentView = mInflater.inflate(layoutId, null, false);
if (mInflater == null || mContentView == null) {
throw new RuntimeException(
"ViewFinder init failed, mInflater == null || mContentView == null.");
}
}
/** @return 當前持有的 ContentView */
public static View getContentView() {
return mContentView;
}
/**
* 泛型查找。先查緩存,命中則直接返回;未命中再從 ContentView 中查找並寫入緩存。
*
* @param viewId 控件 id
* @return 目標 View,找不到時返回 null
*/
@SuppressWarnings("unchecked")
public static <T extends View> T findViewById(int viewId) {
View targetView = mViewMap.get(viewId);
if (targetView == null) {
targetView = mContentView.findViewById(viewId);
mViewMap.put(viewId, targetView);
}
return targetView == null ? null : (T) targetView;
}
}
1. 泛型方法的類型推導
public static <T extends View> T findViewById(int viewId) 中的 T 是方法級泛型,編譯器會根據賦值目標自動推導。這也是 @SuppressWarnings("unchecked") 存在的原因——運行時的實際轉換由虛擬機在第一次使用該引用時完成。
2. SparseArray 而非 HashMap
key 是 int 基本類型,用 SparseArray 可以省去 Integer 的裝箱拆箱,內存與性能都更友好。
3. 緩存的作用
findViewById 需要遍歷整棵 View 樹,層次深、控件多時開銷不小。緩存之後,同一個 id 只會真正查找一次。這與 ListView 中 ViewHolder 的思路是一致的。
4. 靜態變量的使用限制
這裡的 mContentView 與 mViewMap 都是靜態的,意味著 ViewFinder 同一時間只能服務一個佈局。在通用 Adapter 的場景中,因為每次 getViewHolder 都會重新調用 initContentView,所以不會出問題。但如果要在同一頁面同時管理多個不同佈局,就需要改造為實例化設計,把 these 字段變成成員變量。
ViewFinder 的思路非常簡單,卻能切實改善代碼的可讀性與安全性:泛型消掉強制轉換,緩存減少重複查找,初始化失敗時主動拋異常而非靜默返回 null。
當然,如果項目中已經引入了 ButterKnife 這類成熟的注入框架,直接用註解方式會更優雅。但理解 ViewFinder 的實現過程,有助於我們明白那些「一行註解搞定」的框架背後到底做了什麼。
Android AsyncTask 異步任務加載圖片實戰與源碼解析
一、為什麼需要異步任務 Android 的 UI 線程如果被阻塞超過 5 秒,就會引發 ANR(Application Not Responding)異常;而如果用戶等待
Android App 透過 Intent 互相呼叫的實用指南
在 Android 應用開發中,Intent 是連結不同應用與元件的重要橋樑。它讓應用可以不必自行實作地圖、電話或郵件等功能,而是把「想要完成的操作」交給系統,由系統找出
從零剖析網絡請求框架 SimpleNet 的設計與實現
前言 前面我們介紹了 SimpleNet 網絡框架的基本結構,今天我們就從程式碼的角度切入,剖析這個框架的實現。在拆解的同時,我們也會探討背後的設計思路,以及為何要這樣做
Android 中使用自定義字體
前言 Android 自帶一套默認字體,但有時候我們並不想用它,而是想用楷體、隸書之類的字體來呈現文字。那該怎麼做呢?本文就來說明如何在自己的應用中使用自定義字體。 實