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

Cannot inject view to custom class with RoboGuice

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

根据 RoboGuice's example 我对我的习惯做了同样的事情 class:

测试活动

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

测试视图

 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 为空。

如果可以请帮忙

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

希望这对你有用:

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

除了前面的回答之外,您还应该使用以下方法真正开始使用注入的视图:

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

    someTextView.setText("Some text");
}