Simple Example
RoboGuice uses Google's own Guice library, bringing simple and easy-to-use dependency injection to Android. If you have used Spring or Guice, you may already know how convenient this programming method is.
To give you an intuitive image, let's take a look at a typical example:
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 );
}
}
This example contains 19 lines of code. If you read the code of the onCreate () method, you must skip five lines of initialization code to see the truly meaningful code name. setText (). If it is a complex activity, there will be more such initialization code.
The code for implementing the same function using RoboGuice is as follows:
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 );
}
}
In this example, the code of the onCreate () method looks much simpler. The platform-related code has been isolated, and the rest is the real application logic. Do you need a system service? Inject one. Do you need a View or Resource? Also inject one. RoboGuice helps you implement these details.
RoboGuice aims to focus your code on applications, rather than Initialization and maintenance of the lifecycle.
Visit the Installation page to see more details about configuring the RoboGuice application.
Supplementary example
If you want to see what functions RoboGuice can implement, you can access the example directory of Astroboy example.
Http://code.google.com/p/roboguice/wiki/SimpleExample