xutil3學習筆記系列(一)——view工具之註解設計

xUtil3 view()設計之註解設計

對View處理無非就是兩件事:
1. 對View進行賦值;
2. 對View添加相應的監聽事件;

同時Layout佈局文件也是View的子類,但Layout是依託Activity或Fragment等存在的,所以單獨處理,因而定義瞭如下三類註解:

a). ContentView:用來表示將要顯示最頂層View,以Activity爲例,通常爲Layout,用來加載相關的佈局View,會委託setContentView()函數進行處理

package org.xutils.view.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ContentView {
    int value();    
}

其中的value()定義爲int類型,其實是用的資源id來表示,大部分爲R.layout.activity_main。
b). ViewInject:用來對View進行注入賦值,基本上是調用findViewById來完成。

package org.xutils.view.annotation;

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 ViewInject {

    int value();

    /* parent view id */
    int parentId() default 0;
}

其中value爲id,parentId有默認值爲0,當parentId > 0時,代表有父容器。
c). Event: 對View的事件進行處理的註解

package org.xutils.view.annotation;

import android.view.View;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 事件註解.
 * 被註解的方法必須具備以下形式:
 * 1. private 修飾
 * 2. 返回值類型沒有要求
 * 3. 參數簽名和type的接口要求的參數簽名一致.
 * Author: wyouflf
 * Date: 13-9-9
 * Time: 下午12:43
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Event {

    /**
     * 控件的id集合, id小於1時不執行ui事件綁定.
     *
     * @return
     */
    int[] value();

    /**
     * 控件的parent控件的id集合, 組合爲(value[i], parentId[i] or 0).
     *
     * @return
     */
    int[] parentId() default 0;

    /**
     * 事件的listener, 默認爲點擊事件.
     *
     * @return
     */
    Class<?> type() default View.OnClickListener.class;

    /**
     * 事件的setter方法名, 默認爲set+type#simpleName.
     *
     * @return
     */
    String setter() default "";

    /**
     * 如果type的接口類型提供多個方法, 需要使用此參數指定方法名.
     *
     * @return
     */
    String method() default "";
}

以上是xUtil3的與View相關的幾類註解的設計,註解的註釋相當詳細,將在接下來的篇幅中討論各註解的使用方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章