Saturday, December 14, 2013

Android RoboGuice - Let’s slim down the code

Usage of RoboGuice library:

  • Views Injection:: To initialize views, use @InjectViews, for example: @InjectView( TextView textView1;
  • Resources Injection: To initialize and get resources, use @InjectResources, for example: @InjectResource(R.string.app_name) String name;
  • System services Injection: To initialize and access system services, use @Inject, for example: @Inject LayoutInflater inflater;
  • POJO object Injection: To inject and initialize POJO object, use @Inject, for example: @Inject Foo foo;
General Activity :

public class TestActivity extends Activity{
    TextView textView1;
    TextView textView2;
    ImageView imageView1;
    String name;
    Drawable icLauncher;
    LocationManager locManager;
    LayoutInflater inflater;
    NotificationManager notifyManager;
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        textView1 = (TextView) findViewById(;
        textView2 = (TextView) findViewById(;
        imageView1 = (ImageView) findViewById(;
        name = getString(R.string.app_name);
        icLauncher = getResources().getDrawable(;
        locManager = (LocationManager) getSystemService(Activity.LOCATION_SERVICE);
        inflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        notifyManager = (NotificationManager) getSystemService(Activity.NOTIFICATION_SERVICE);
        textView1.setText("Hello World! RoboGuice demo");

Let’s check the magic of RoboGuice and let’s slim down the code.
public class TestActivity extends RoboActivity{

        @InjectView( TextView textView1;

        @InjectView( TextView textView2;

        @InjectView( ImageView imageView1;

        @InjectResource(R.string.app_name) String name;

        @InjectResource(R.drawable.ic_launcher) Drawable icLauncher;

        @Inject LocationManager locManager;

        @Inject LayoutInflater inflater;

        @Inject NotificationManager notifyManager;

       @Override        protected void onCreate(Bundle savedInstanceState) {

              // TODO Auto-generated method stub 





To use RoboGuice, you need to download following JAR files and add them to your claspath:

No comments:

Post a Comment