6

我想将一些视图从 xml 布局注入到 RoboFragment,但不幸的是我得到了 Nullpointer 异常。由于 RoboGuice(除了是一个很棒的 DI 框架)的文档很少,我不知道我是否可以@ContentView(R.layout.fragmentlayout)用来注释我的 RoboFragment。有什么我应该做的吗?我目前做的是:

public class TestFragment extends RoboFragment {

    @InjectView(R.id.upBtn) private Button upBtn;   

    @Override
    public View onCreateView(LayoutInflater layoutInflater, 
            ViewGroup container, Bundle savedInstanceState) {

        super.onCreateView(layoutInflater, container, savedInstanceState);
        View view = layoutInflater.inflate(R.layout.fragmentlayout, container, false);
        RoboGuice.getInjector(getActivity()).injectMembers(this);
        upBtn.setSelected(false);   // <------ Null pointer here
        return view;
    }
}
4

2 回答 2

14

如果您查看 RoboFragment 的源代码,您会看到

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    RoboGuice.getInjector(getActivity()).injectViewMembers(this);
}

如果您坚持手动注入,请使用injectViewMembers(). 如果您可以延迟触摸视图直到 之后onViewCreated(),那么它将为您设置。

于 2013-01-15T18:05:49.993 回答
-3

您需要返回视图。upBtn.setSelected(false) 之后;

public View onCreateView(LayoutInflater layoutInflater, ViewGroup container, Bundle savedInstanceState) {

    super.onCreateView(layoutInflater, container, savedInstanceState);
    View view = layoutInflater.inflate(R.layout.fragmentlayout, container, false);
    RoboGuice.getInjector(getActivity()).injectMembers(this);
    upBtn = (Button) view.findViewById(YOUR_ID); // Initialization
    upBtn.setSelected(false);   // <------ Null pointer here
 return view;
}
于 2013-01-08T14:09:19.017 回答