編輯:關於 Android 開發
每次寫 findViewById 都是一種消耗。既然 Java 從 5 就提供了註解與反射,我們完全可以自己造一個輕量版的 @BindView,告別重複勞動。整個方案只需要兩個類。
用 @Target(ElementType.FIELD) 限定它只能標在字段上,@Retention(RetentionPolicy.RUNTIME) 保證運行時可讀;另外留一個 click 開關,順手把點擊監聽也綁定掉。
package com.practice.noyet.coolweather.util;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BindView {
int id();
boolean click() default false;
}
核心邏輯是遍歷當前對象的所有字段,找出帶 @BindView 的,然後用反射塞值。這裡有幾個實務細節值得注意:
field.setAccessible(true):不然無法寫入 private 字段。package com.practice.noyet.coolweather.util;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.util.Log;
import android.view.View;
import java.lang.reflect.Field;
public class AnnotateUtil {
public static void initBindView(Object currentClass, View sourceView) {
Field[] fields = currentClass.getClass().getDeclaredFields();
if (fields != null && fields.length > 0) {
for (Field field : fields) {
BindView bindView = field.getAnnotation(BindView.class);
if (bindView != null) {
int viewId = bindView.id();
boolean clickLis = bindView.click();
try {
field.setAccessible(true);
if (clickLis) {
sourceView.findViewById(viewId)
.setOnClickListener((View.OnClickListener) currentClass);
}
field.set(currentClass, sourceView.findViewById(viewId));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public static void initBindView(Activity aty) {
initBindView(aty, aty.getWindow().getDecorView());
}
public static void initBindView(View view) {
Context cxt = view.getContext();
if (cxt instanceof Activity) {
initBindView((Activity) cxt);
} else {
Log.d("AnnotateUtil.java", "the view don't have root view");
}
}
@TargetApi(11)
public static void initBindView(Fragment frag) {
initBindView(frag, frag.getActivity().getWindow().getDecorView());
}
}
在 Activity 或 Fragment 中,只需一行註解加一行初始化:
@BindView(id = R.id.headerlayout)
private HeaderLayout headerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather);
AnnotateUtil.initBindView(this);
}
在 Adapter 的 ViewHolder 中,把 sourceView 傳進去即可,這正是它比 findViewById 更清爽的地方——ViewHolder 場景下不再需要為每個控件寫一遍轉型:
package com.practice.noyet.coolweather.adapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.practice.noyet.coolweather.model.County;
import com.practice.noyet.coolweather.util.AnnotateUtil;
import com.practice.noyet.coolweather.util.BindView;
public class SpinnerArrayAdapter extends BaseAdapter<County> {
private LayoutInflater mInflater;
public SpinnerArrayAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
Holder holder;
if (view == null) {
view = mInflater.inflate(android.R.layout.simple_list_item_1, null);
holder = new Holder(view);
view.setTag(holder);
} else {
holder = (Holder) view.getTag();
}
County county = (County) getItem(position);
holder.textView.setText(county.getCountyName());
return view;
}
private class Holder {
@BindView(id = android.R.id.text1)
public TextView textView;
public Holder(View view) {
AnnotateUtil.initBindView(this, view);
}
}
}
要提醒的是,反射本身有性能成本,因此這個方案不適合放在 getView 這種高頻調用路徑上反覆執行。示例中之所以沒問題,是因為解析只在 ViewHolder 首次創建時進行,後續都走 view.getTag() 複用。正式專案若追求極致性能,ButterKnife 這類基於編譯期注解處理的方案會更合適;但如果你只是想理解原理、或需要在無法引入第三方庫的環境裡自己搞定,這份五十行的實現已經足夠。
Android 隱藏標題欄的三種常見做法
在 Android 開發中,若希望自訂畫面不被預設標題欄影響,可以透過程式碼或主題設定隱藏標題欄。方法一:requestWindowFeature在 Activity 中
Android WindowManager 窗口管理服務實戰
Android WindowManager 窗口管理服務實戰WindowManager 是 Android 系統中負責窗口管理的底層服務。許多常見 UI 能力,如 Act
在 Android 中生成 Excel 檔案並儲存到本機
在 Android 中生成 Excel 有些專案會需要在客戶端直接產生 Excel 檔案,再提供給使用者下載或寄送。本文以訂單資訊為例,說明如何在 Android 中建立
Tomcat + Java 的 Web 程序持續佔用 CPU 問題排查
Tomcat + Java 的 Web 程序持續佔用 CPU 問題排查 現象: 在 Tomcat 中部署 Java 的 Web 應用程序,運行一段時間後,Tomcat 的