編輯:關於 Android 程式設計
本文重點講解如何用注解來實現 findViewById 的功能。在動手之前,我們先熟悉一下 Java 中如何定義與解析一個注解。
注解的概念是在 JDK 5.0 中提出來的,java.lang 包裡已經內置了三個常用注解:Override、Deprecated、SuppressWarnings。Override 表示這個方法重寫了父類的方法;Deprecated 表示該方法或屬性在新版本中已不建議使用;SuppressWarnings 則用來屏蔽一些警告。
注解的定義和接口非常像,只是在 interface 前面多了一個 @:
public @interface TestPerson {
}
千萬別把前面的 @ 弄丟了,否則就成了普通的接口定義。注解和類一樣也可以定義屬性:
public @interface TestPerson {
// name 既是屬性也是方法,gavin 是默認值
String name() default "gavin";
}
比如我們定義兩個注解:一個用來說明某個類的用途,另一個用來說明類中的某個方法由誰測試:
// 標注某個類的用途
public @interface ClassFunction {
String value() default "";
}
// 標注類中的方法由誰測試
public @interface TestPerson {
String name() default "gavin";
}
那如何限定一個注解用在類上還是方法上呢?我們看看 Override 和 Deprecated 的實現:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override { }
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
public @interface Deprecated { }
這裡的 Target 和 Retention 叫做元注解。
Target 用來表明注解的作用對象,其值是一個枚舉:
CONSTRUCTOR(構造器)、FIELD(域)、LOCAL_VARIABLE(局部變量)、METHOD(方法)、PACKAGE(包)、PARAMETER(參數)、TYPE(類、接口或 enum 聲明)。
Retention 用來說明注解的生命週期,即什麼時候失效:
SOURCE(源文件階段有效)、CLASS(class 文件階段有效)、RUNTIME(運行時有效)。
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestPerson {
String name() default "gavin";
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ClassFunction {
String value() default "";
}
// 使用
@ClassFunction("用於描述一個人的基本信息")
public class Person {
@TestPerson(name = "jj")
public void setName() { }
}
要說明的一點是:如果某個注解屬性以 value 命名(如 ClassFunction 中的 value),賦值時可以直接寫 @ClassFunction("...");但如果用的是其他名稱,就必須寫成 @TestPerson(name = "jj") 的形式。
public class Main {
public static void main(String[] args) {
Person person = new Person();
Class clazz = Person.class;
try {
Method method = clazz.getMethod("getName", null);
if (method.isAnnotationPresent(TestPerson.class)) {
method.invoke(person, null);
TestPerson test = method.getAnnotation(TestPerson.class);
String name = test.name();
System.out.println("this method is test by--> " + name);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
理解了定義與解析,我們就能動手改造 findViewById 了。先定義一個注解:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface InjectView {
int id() default -1; // 控件 id
}
再在 Activity 中通過反射完成注入:
public class MainActivity extends Activity {
// 標注 TextView 的 id
@InjectView(id = R.id.tv_img)
private TextView mText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
autoInjectAllField(this);
} catch (Exception e) {
e.printStackTrace();
}
if (mText != null) mText.setText("Hello Gavin");
}
public void autoInjectAllField(Activity activity) throws IllegalAccessException, IllegalArgumentException {
Class clazz = this.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(InjectView.class)) {
InjectView inject = field.getAnnotation(InjectView.class);
int id = inject.id();
if (id > 0) {
field.setAccessible(true); // 反射訪問私有成員必須加這句
field.set(activity, activity.findViewById(id));
}
}
}
}
}
這樣,原本冗餘的 findViewById 調用,就被一個簡潔的 @InjectView 注解替代了。這也正是如今眾多依賴注入框架(如 ButterKnife)的實現思路雛形。
Android 屬性動畫入門:ValueAnimator、插值器與 TypeEvaluator 逐個拆解
前面寫了兩篇 Tween 動畫的文章,如果都讀懂了,日常使用大致沒問題。但也提過 Tween 動畫在交互上有天生缺陷——它只改動畫的「視覺呈現」,並不改變控制項真正的位置
百度地圖 Android 開發踩坑與 Marker 定位實作
在 Android 專案中整合百度地圖時,常見問題包括 API Key 設定、定位服務初始化、MapView 生命週期管理,以及 Marker 資訊傳遞。以下整理實作時容
仿微博資訊流:自定義下拉刷新 ListView 的 Adapter 與圖片異步載入
本文是仿新浪微博系列的一環,重點放在 Adapter 與圖片異步載入這兩塊。自定義的 PullToRefreshListView 直接繼承 ListView,並在頭部插入
解決 Virtualbox 虛擬機下 Android x86 4.0 無法聯網的問題
自從 Android x86 問世後,越來越多人開始在虛擬機上安裝體驗,但安裝過程並不簡單,網上因而出現各種教學。其中,Virtualbox 虛擬機下的 Android