天天看點

android webview annotation,Android中Annotation使用

首先建立一個項目:

android webview annotation,Android中Annotation使用

這個項目很簡單,就三個類,一個activity,一個注解,一個注解工具類,首先看一下activity中的代碼:

package com.gefufeng.annotationdemo;

import android.app.Activity;

import android.os.Bundle;

import android.widget.TextView;

public class MainActivity extends Activity {

@ViewInject(value = R.id.text,defaultText = "你好注解")

private TextView text;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

InjectUtils.init(this);

}

}

這個activity非常簡單,就是為了示範annotation用的,其中有一個Textview,id為R.id.text,然後我為它加上了一個自定義注解Viewinject,下面看一下這個注解:

package com.gefufeng.annotationdemo;

import java.lang.annotation.Documented;

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)

@Documented

public @interface ViewInject {

int value();

String defaultText();

}

這個注解中我先簡單的介紹一下幾個名詞:

[email protected] : 加上它ViewInject就表示一個自定義的注解

[email protected] :表示這個注解是給誰用的,是一個類的,還是一個方法呢,還是一個變量呢,等等

[email protected]:這個注解的生命周期,有的注解在原檔案中有效,有的在class檔案中還有效,有的在運作時還有效

[email protected]:Documented是一個标記注解,沒有成員,用于描述其它類型的annotation應該被作為被标注的程式成員的公共API

OK,注解中有兩個方法,就是聲明了兩個參數,方法的名稱就是參數的名稱。

下面看一下InjectUtils類:

package com.gefufeng.annotationdemo;

import java.lang.reflect.Field;

import android.app.Activity;

import android.view.View;

import android.widget.TextView;

public class InjectUtils {

public static void init(Activity ac){

Class> c = ac.getClass();

Field[] fields = c.getDeclaredFields();

for (Field f : fields) {

ViewInject viewInject = f.getAnnotation(ViewInject.class);

if (viewInject != null) {

int id = viewInject.value();

String defaultText = viewInject.defaultText();

View view = ac.findViewById(id);

if (view instanceof TextView) {

((TextView)view).setText(defaultText);

}

f.setAccessible(true);

try {

f.set(ac, view);

} catch (IllegalAccessException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IllegalArgumentException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

}

這個類也比較簡單,就一個靜态的init方法,用于在activity中初始化。

首先找出activity中公開的變量,然後周遊這些變量,查找哪些變量有ViewInject注解,如果有,取出value和defaultText的值,最後調用f.set(ac, view);對于field.set()方法,源碼中的解釋為:

Sets the value of the field in the specified object to the value. This reproduces the effect of {@code object.fieldName = value}

OK,一個注解初始化view的例子到此完成,運作這個android程式,這個textview就已被初始化,預設值為“你好注解”。

關于注解的知識這裡沒做系統的介紹,隻是在android示範了怎麼使用注解