Can't inject view into custom class using RoboGuice

I started using RoboGuice in my project. I can easily inject views inside fragments and actions, but I have some problems with cusom views. I was getting a null ptr exception every time.

As per RoboGuice example, I did the same with my custom class:

TestActivity

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


}

      

The xml login is in pastebin here.

Testing scheme

<?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 always says it is null. logInTab

Please help if you can.

+3


source to share


2 answers


I don't know why there are no code examples in it, but when I have to inject custom views, I use addViewMembers.

Hope this work for you:



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

      

+5


source


In addition to the previous answer, you should use the following method to actually start using the views you entered:



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

    someTextView.setText("Some text");
}

      

+1


source







All Articles