Android & RoboGuice - Inject views on Fragment?

aryaxt picture aryaxt · Mar 20, 2012 · Viewed 8.3k times · Source

I have a fragment that I need to display on the screen. I want to be able to use InjectView to inject my UI elements. InjectView works fine on activities because the view (xml) is set during onCreate, however on fragments the view is set on onCreatView.

So is there a way to use InjectView on fragments? I know that I could use findViewbyId to find each element, but I rather use InjectView

public class ProfileFragment extends RoboDialogFragment {

    @InjectView(R.id.commentEditText)
    protected EditText commentEditText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

            // I get a  null pointer exception here
            commentEditText.setText("Some comment");

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.profile , container, false);

            // I get a  null pointer exception here
        commentEditText.setText("Some comment");

        return view;
    }

}

Answer

aryaxt picture aryaxt · Mar 20, 2012

Injection happens during onViewCreated

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

    commentEditText.setText("Some comment");
}