RoboFragment中的InjectView

时间:2013-01-08 07:56:03

标签: android dependency-injection roboguice

我想从xml布局向RoboFragment注入一些视图但不幸的是我得到了Nullpointer Exception。由于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;
    }
}

1 个答案:

答案 0 :(得分:-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;
}