Skip to content

Your First View Injection

emmby edited this page Oct 27, 2014 · 2 revisions

Overview

To inject your first view into an activity, you'll need to:

  1. Inherit from RoboActivity
  2. Set your content view
  3. Annotate your views with @InjectView

Your First View Injection

Injecting views into your RoboGuice activities is simple. First, create a new Activity that inherits from RoboActivity:

    public class MyActivity extends RoboActivity {
        ...
    }

Then add a layout to the activity:

    // Override onCreate() and call setContentView()
    public class MyActivity extends RoboActivity {

        @Override
        protected void onCreate( Bundle savedState ) {
            setContentView(R.layout.myactivity_layout);
        }
    }

Assuming that the myactivity_layout.xml file contains a TextView with id text1, you can now inject that view into your activity and use it without having to call findViewById()

    public class MyActivity extends RoboActivity {
        @InjectView(R.id.text1) TextView textView;

        @Override
        protected void onCreate( Bundle savedState ) {
            setContentView(R.layout.myactivity_layout);
            textView.setText("Hello!");
        }
    }

That's it! You've injected your first view!

@ContentView annotation

The @ContentView annotation can be used to further alleviate development of activities and replace the setContentView statement :

    @ContentView(R.layout.myactivity_layout)
    public class MyActivity extends RoboActivity {
        @InjectView(R.id.text1) TextView textView;

        @Override
        protected void onCreate( Bundle savedState ) {
            textView.setText("Hello!");
        }
    }

More View Injections

View injection doesn't end with TextViews of course. You can inject any kind of view that you want, even custom views. The only constraint of course is that the type of view you inject must agree with the type in the layout.

There's no reason you have to stick with XML layouts either. You can also inject views for activities that have their content views constructed manually using java code.

Views can also be injected into Fragments & Views as well.

Injecting Views into Fragments

When using Fragments, View injection happens during onViewCreated(). So after super.onViewCreated() is called, you can start using your injected views. For example:

@InjectView TextView commentEditText;

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    commentEditText.setText("Some comment");
}
Clone this wiki locally