【十一】注入框架RoboGuice使用:(Your First Injection into a Custom View class)

来源:互联网 发布:魅族阿里云系统好用吗 编辑:程序博客网 时间:2024/05/15 02:27

          上一篇我们简单的介绍了一下RoboGuice的使用(【十】注入框架RoboGuice使用:(Your First Testcase)),今天我们来看下自定义View的注入(Custom View)。

          在开始本文之前,你先要熟悉普通Java对象的注入(点击进入)。在RoboGuice 3.0版本中你同样给自定义View(Custom View)进行诸如。

class MyView extends View {    @Inject Foo foo;     @InjectView(R.id.my_view) TextView myView;    public MyView(Context context) {        inflate(context,R.layout.my_layout, this);        RoboGuice.getInjector(getContext()).injectMembers(this);    }    public MyView(Context context, AttributeSet attrs, int defStyle) {        super(context, attrs, defStyle);        inflate(context,R.layout.my_layout, this);        RoboGuice.getInjector(getContext()).injectMembers(this);    }    public MyView(Context context, AttributeSet attrs) {    super(context, attrs);        inflate(context,R.layout.my_layout, this);        RoboGuice.getInjector(getContext()).injectMembers(this);    }    @Override    public void onFinishInflate() {        super.onFinishInflate();        //All injections are available from here        //in both cases of XML and programmatic creations (see below)        myView.setText(foo.computeFoo());    }}
      在Android中,我们可以通过两种方法进行创建View:

       ①:自动从XML进行加载

       ②:程序方法,使用new CustomView(Context context)进行创建

 使用RoboGuice 3.0版本,在任何情况下,你都要确保通过显式注入,获取来自RoboGuice的注入。

 在Roboguice 3.1版本,就会些区别:

       Roboguice 3.1完全通过XML加载并且自动注入View中所有的子控件,在XML加载过程中需要注意:该会自动回调onFinishInflate()方法。然而如果你自己提供额外的构造函数,那么你需要负责通过RoboGuice进行注入。

       在后一种情况中,在构造函数的末尾调用onFinishInflate()方法。如果你希望使用RoboGuice模板,你可以更好的使用该回调方法来处理所有的构造函数,你的自定义视图将会被注入。

        下面是一个例子:

class MyView extends View {    @Inject Foo foo;     @InjectView(R.id.my_view) TextView myView;    public MyView(Context context) {        inflate(context,R.layout.my_layout, this);        RoboGuice.getInjector(getContext()).injectMembers(this);        onFinishInflate();    }    public MyView(Context context, AttributeSet attrs, int defStyle) {        super(context, attrs, defStyle);        inflate(context,R.layout.my_layout, this);    }    public MyView(Context context, AttributeSet attrs) {    super(context, attrs);        inflate(context,R.layout.my_layout, this);    }    @Override    public void onFinishInflate() {        super.onFinishInflate();        //All injections are available from here        //in both cases of XML and programmatic creations (see below)        myView.setText(foo.computeFoo());    }}


    

1 0
原创粉丝点击