2013-06-26 20 views
0

我的目標是能夠註釋基於Te​​xtView的類,以便我可以在它們上注入自定義字體,而無需搜索我的整個(和龐大的)代碼庫。由於我有一個AspectJ Android項目,所以AOP看起來很不錯。使用AspectJ捕獲Android中帶註釋的小部件的初始化/設置

我開始通過定義以下注釋:

@Target(ElementType.FIELD) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface InsertFontTypeFace 
{ 
    String typeFacenamePathInAssets() default ""; 
} 

在我的活動我有這樣的事情:

@InsertFontTypeFace(typeFacenamePathInAssets="fonts/myCustomFont.ttf") 
private Button myButton; 

最後,在我的方面,我有:

pointcut textViewBasedWidgetInitialization(TextView thisObject, InsertFontTypeFace annotation): initialization(TextView+.new(..)) && @annotation(annotation) && target(thisObject); 

after(TextView thisObject, InsertFontTypeFace annotation) : textViewBasedWidgetInitialization(thisObject, annotation) 
{ 
    String pathToFont = annotation.typeFacenamePathInAssets(); 

    if(! EMPTY_STRING.equals(pathToFont)) 
    { 
     Typeface myTypeface = Typeface.createFromAsset(thisObject.getContext().getAssets(), pathToFont); 
     thisObject.setTypeface(myTypeface); 
    } 
} 

我也嘗試用以下切入點來捕獲現場設置:

pointcut textViewBasedWidgetInitialization(TextView thisObject, InsertFontTypeFace annotation): set(TextView+ *.*) && @annotation(annotation) && target(thisObject); 

這兩個選項都會在Eclipse中產生「在XXX中定義的建議未應用」警告。

任何人都可以對此有所瞭解嗎?

在此先感謝。

回答

0

好吧,我不認爲我有完美的解決方案,但我有一個解決方案,正在做我想要的。這裏是代碼:

pointcut textViewBasedWidgetInitialization(InsertFontTypeFace annotation): set(TextView+ Activity+.*) && @annotation(annotation); 

after (InsertFontTypeFace annotation, Object targetObject): textViewBasedWidgetInitialization(annotation) && args(targetObject) 
{ 
    if(targetObject != null) 
    { 
     TextView widget = (TextView) targetObject; 

     String pathToFont = annotation.typeFacenamePathInAssets(); 

     if(! EMPTY_STRING.equals(pathToFont)) 
     { 
      Typeface myTypeface = Typeface.createFromAsset(widget.getContext().getAssets(), pathToFont); 
      widget.setTypeface(myTypeface); 
     } 
    } 
} 

我只是捕獲設置一個TextView子類註解@InsertFontTypeFace部分。之後,我建議減少點數,同時捕獲參數(這將是小部件!!)。我嘗試過使用this()和target(),但它們總是捕獲Activity而不是Widget。我也嘗試過around()返回()和變體,但我無法使它工作,因爲繼續()必須採取相同數量的參數比點切,我確實需要捕獲的註釋。

嗯,這是一種解決方案。如果有人有更好的貢獻,我希望看到它。