[翻译]RoboGuice使用示例

简单示例

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

为了给大家一个直观的映像,下面我们来一起来看看一个典型的示例:

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 );
   
}
}

这个示例一共是19行代码。如果你阅读onCreate()方法的代码,你必须略过5行初始化的代码才能看到真正有意义的代码name.setText()。如果是复杂的activity的话,那就会有更多的这样的初始化代码。

我们使用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 );
   
}
}

这个示例中,onCreate()方法的代码粗略看起来简单多了。和平台相关的代码都已经被单独隔离起来了,剩下的就是真正的应用逻辑。你需要一个系统服务么?注入一个。你需要一个View或者Resource么?也注入一个。RoboGuice 帮你实现这些细节。

RoboGuice 的目的是让你的代码关注于应用,而不是初始化、维护生命周期等工作。

访问 Installation 页面刻意看到更多的配置RoboGuice应用的细节。


补充示例

如果你还想看看 RoboGuice 可以实现哪些功能,可以去访问 Astroboy example 的示例目录

http://code.google.com/p/roboguice/wiki/SimpleExample

posted @ 2011-05-31 19:31  熊波  阅读(3520)  评论(1编辑  收藏  举报