Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 中用自定義注解替代 findViewById 的實現

編輯:關於 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

理解了定義與解析,我們就能動手改造 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)的實現思路雛形。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved