`

roboguice - Android上的依赖注入框架

阅读更多

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

 

如果用过大名鼎鼎的Spring(轻量级的J2EE框架),就会知道Spring的核心思想就是“依赖注入”。

Google贡献了一个开源项目,用于在Android上使用依赖注入机制。

 

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

 

如果使用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 ); 
    } 
} 

 

所以,如果大家要从头开发一个崭新的程序的话,可以考虑使用这些前卫的技术。

  • 大小: 70.7 KB
1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics