Android Afinal框架学习(二) FinalActivity 一个IOC框架

时间:2021-12-27 04:35:49

框架地址:https://github.com/yangfuhai/afinal

相应的源代码:

net.tsz.afinal.annotation.view.*

FinalActivity

FinalActivity是一个基础类,结合注解实现了,依赖注入(view的资源id,经常使用的监听器), 利用set方式注入

全然注解方式就能够进行UI绑定和事件绑定,无需findViewById和set event Listener

这个过程:initInjectedView>findViewById、setListener(activity, activity.field, eventLocalMethod, eventType)>

1.依据id得到view对象,设置到activity相应的field中

2. switch(eventType) {

case event:

view.set event listener(new EventListener(activity, eventLocalMethod));

EventListener implements many event listener>

在相应的event的重写方法中,反射调用eventLocalMethod

这些eventLocalMethod 的參数须要与 相应的系统 event method 的參数一致

...

}

注解有哪些类型:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ViewInject {
public int id();
public String click() default "";
public String longClick() default "";
public String itemClick() default "";
public String itemLongClick() default "";
public Select select() default @Select(selected="") ;
}

调用注解:

package com.stone.afinal;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.Select;
import net.tsz.afinal.annotation.view.ViewInject;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView; public class MainActivity extends FinalActivity {
@ViewInject(
id = R.id.imageview,
click = "myClick",
longClick = "myLongClick")
ImageView imageview; @ViewInject(
id = R.id.listview,
click = "myClick",
itemLongClick = "myItemLongClick",
itemClick = "myItemClick",
longClick = "myLongClick",
select = @Select(selected="myItemSelected", noSelected="myNoSelected"))
ListView listView; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);//继承FinalActivity,setContentView中初始化了
} public void myClick(View v) {
System.out.println("--myClick--");
}
public void myLongClick(View v) {
System.out.println("--myLongClick--");
}
public void myItemLongClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
System.out.println("--myItemLongClick--");
}
public void myItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
System.out.println("--myItemClick--");
}
public void myItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
System.out.println("--myItemSelected--");
} public void myNoSelected(AdapterView<?> arg0) {
System.out.println("--myNoSelected--");
}
}

在其它侵入式框架下使用(如ActionBarShelock)

     protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(view);
FinalActivity.initInjectedView(this);
}

在Fragment中使用

     public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View viewRoot = inflater.inflate(R.layout.map_frame, container, false);
FinalActivity.initInjectedView(this,viewRoot);
}