15

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;
    }

}
aryaxt
  • 76,198
  • 92
  • 293
  • 442
  • Please star the Roboguice issue (http://code.google.com/p/roboguice/issues/detail?id=160&q=contentview) to show the developers this should be added – Diederik Jun 08 '12 at 08:20

1 Answers1

27

Injection happens during onViewCreated

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

    commentEditText.setText("Some comment");
}
aryaxt
  • 76,198
  • 92
  • 293
  • 442
  • 2
    we'll work on getting better docs for 2.0 now that it's in release candidate – emmby Mar 20 '12 at 22:56
  • @emmby Any luck with the docs? It's been released for a minute now, and the docs are still lacking, at least for a good and thorough example of Fragments. – Christopher Perry Jan 15 '13 at 23:34
  • we're working on the docs now. they're getting better, but still not there yet: https://github.com/emmby/roboguice/wiki – emmby Jan 16 '13 at 18:23
  • @emmby it's been 2 and a half years and this very basic and common idiom in roboguice is still not documented! – Merk Oct 10 '14 at 15:46
  • Hah! Good point, done: https://github.com/roboguice/roboguice/wiki/Your-First-View-Injection – emmby Oct 27 '14 at 16:57