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

          上一篇我们简单的介绍了一下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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值