15

我有一个片段需要在屏幕上显示。我希望能够用来InjectView注入我的 UI 元素。InjectView 在活动上工作正常,因为视图(xml)是在 期间设置的onCreate,但是在片段上,视图设置在onCreatView.

那么有没有办法在片段上使用 InjectView 呢?我知道我可以使用 findViewbyId 来查找每个元素,但我宁愿使用 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;
    }

}
4

1 回答 1

27

注射发生在onViewCreated

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

    commentEditText.setText("Some comment");
}
于 2012-03-20T17:46:56.697 回答