无法使用RoboGuice将视图注入自定义类

时间:2015-06-08 09:57:03

标签: android nullpointerexception roboguice

我开始在我的项目中使用RoboGuice。我可以轻松地在片段和活动中注入视图,但我在使用cusom视图时遇到了一些麻烦。 我每次都得到null ptr异常。

根据RoboGuice's example我对我的自定义类做了同样的事情:

测试活动

@ContentView(R.layout.test_layout)
public class TestActivity extends RoboActivity {

    @InjectView(R.id.testView_1) TestView testView;

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

TestView

 public class TestView extends LinearLayout {


    @InjectView(R.id.log_in_tab) View logInTab;

    public TestView(Context context) {
        super(context);
        initView();
    }

    public TestView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public TestView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }


    @Override
    public void onFinishInflate() {
        super.onFinishInflate();

        if (logInTab == null)
            Toast.makeText(getContext(), "Still NULL", Toast.LENGTH_LONG).show();
        else
            Toast.makeText(getContext(), "Ok", Toast.LENGTH_LONG).show();

    }

    public void initView() {

        inflate(getContext(), R.layout.login_view, this);
        RoboGuice.injectMembers(getContext(), this);
    }


}

登录视图的xml位于pastebin here.

测试布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <view
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        class="hu.illion.kwindoo.view.test.TestView"
        android:id="@+id/testView_1"/>
</LinearLayout>

Toast总是说 logInTab 为空。

如果可以,请帮忙。

2 个答案:

答案 0 :(得分:5)

我不知道为什么没有代码示例,但是当我必须注入自定义视图时,我使用injectViewMembers。

希望这对你有用:

public void initView() {
    inflate(getContext(), R.layout.login_view, this);
    RoboGuice.injectMembers(getContext(), this);
    RoboGuice.getInjector(getContext()).injectViewMembers(this);
}

答案 1 :(得分:1)

除了上一个答案,您应该使用以下方法实际开始使用注入的视图:

@Override
protected void onFinishInflate() {
    super.onFinishInflate();

    someTextView.setText("Some text");
}
相关问题