`
lizhuang
  • 浏览: 893047 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

RoboGuice入门

阅读更多
参考
https://github.com/roboguice/roboguice/wiki


RoboGuice将简单的依赖注入带给android开发,使用google开发的Guice注入库。如果你曾经使用过Spirng或者Guice,你应该早就知道依赖注入的能够大大简化编程难度。

我们先来看一个典型的Android activity

class AndroidWay extends Activity { 
      TextView name; 
      ImageView thumbnail; 
      LocationManager loc; 
      Drawable icon; 
      String myName; 

      public void onCreate(Bundle savedInstanceState) { 
          super.onCreate(savedInstanceState); 
          setContentView(R.layout.main);
          name      = (TextView) findViewById(R.id.name); 
          thumbnail = (ImageView) findViewById(R.id.thumbnail); 
          loc       = (LocationManager) getSystemService(Activity.LOCATION_SERVICE); 
          icon      = getResources().getDrawable(R.drawable.icon); 
          myName    = getString(R.string.app_name); 
          name.setText( "Hello, " + myName ); 
      } 
  } 


这段代码,大部分的语句都是在做初始化的操作,实际上在业务上起作用的,只有name.setText()这部分。

如果采用RoboGuice
class RoboWay extends RoboActivity { 
      @InjectView(R.id.name)             TextView name; 
      @InjectView(R.id.thumbnail)        ImageView thumbnail; 
      @InjectResource(R.drawable.icon)   Drawable icon; 
      @InjectResource(R.string.app_name) String myName; 
      @Inject                            LocationManager loc; 

      public void onCreate(Bundle savedInstanceState) { 
          super.onCreate(savedInstanceState); 
          setContentView(R.layout.main);
          name.setText( "Hello, " + myName ); 
      } 
  } 

大量的初始化代码被简单的注入的代码替代,代码逻辑更为清晰,只保留了需要的那句name.setText()。

你需要SystemService可以注入,需要View也可以注入。RoboGuice的目标是使开发者关注应用,而不是关注初始化和生命周期。

RoboGuice2.0只要引入4个jar包,或简单的maven配置pom,你就可以拥有这一切。

引入jar看这里
https://github.com/roboguice/roboguice/wiki/InstallationNonMaven
maven管理的看这里
https://github.com/roboguice/roboguice/wiki/InstallationMaven
分享到:
评论
1 楼 xueji5368 2014-01-26  
这个现在已经广泛使用了嘛!

相关推荐

Global site tag (gtag.js) - Google Analytics