Android依赖注入:Google Guice on Android的使用及相关资源

本文转自:http://blog.csdn.net/sangming/article/details/8878104

RoboGuice 使用谷歌自己的Guice库,给Android带来了简单和易用的依赖注入。如果你使用过Spring或Guice的话,你可能已经知道这种编程方式是多么的便捷。

RoboGuice 允许使用annotation 的方式来描述id于View之间的关系,其余的工作由roboGuice库来完成。比如:

[java] view plain copy
  1. class AndroidWay extends Activity {  
  2.  TextView name;  
  3.  ImageView thumbnail;  
  4.  LocationManager loc;  
  5.  Drawable icon;  
  6.  String myName;  
  7.   
  8.  public void onCreate(Bundle savedInstanceState) {  
  9.  super.onCreate(savedInstanceState);  
  10.  setContentView(R.layout.main);  
  11.  name      = (TextView) findViewById(R.id.name);  
  12.  thumbnail = (ImageView) findViewById(R.id.thumbnail);  
  13.  loc       = (LocationManager) getSystemService(Activity.LOCATION_SERVICE);  
  14.  icon      = getResources().getDrawable(R.drawable.icon);  
  15.  myName    = getString(R.string.app_name);  
  16.  name.setText( "Hello, " + myName );  
  17.  }  
  18. }  

如果使用roboguice 来写:

[java] view plain copy
  1. class RoboWay extends RoboActivity {  
  2.  @InjectView(R.id.name)             TextView name;  
  3.  @InjectView(R.id.thumbnail)        ImageView thumbnail;  
  4.  @InjectResource(R.drawable.icon)   Drawable icon;  
  5.  @InjectResource(R.string.app_name) String myName;  
  6.  @Inject                            LocationManager loc;  
  7.   
  8.  public void onCreate(Bundle savedInstanceState) {  
  9.  super.onCreate(savedInstanceState);  
  10.  setContentView(R.layout.main);  
  11.  name.setText( "Hello, " + myName );  
  12.  }  
  13. }  


只需使用@InjectView 来描述 view 和Id之间的关系,RoboGuice 自动完成余下的工作,代码简洁易读。


注意:activity必须继承自RoboActivity


收集到的一些资料:github有资料和源码https://github.com/roboguice/roboguice

中文的资料:http://daimajishu.iteye.com/blog/1610501

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值