3

I started to use RoboGuice within my project. I can easily inject views inside fragments and activites but i have some trouble with cusom views. I got null ptr exception every time.

According to RoboGuice's 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);
    }


}

Login view's xml is in pastebin here.

Test layout

<?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 that logInTab is null.

Please help if you can.

amdixon
  • 3,814
  • 8
  • 25
  • 34
Adam Varhegyi
  • 11,307
  • 33
  • 124
  • 222

2 Answers2

5

I don't know why there is no code examples of that but when i have to inject custom views i use injectViewMembers.

Hope this work for you:

public void initView() {
    inflate(getContext(), R.layout.login_view, this);
    RoboGuice.injectMembers(getContext(), this);
    RoboGuice.getInjector(getContext()).injectViewMembers(this);
}
isma3l
  • 3,833
  • 1
  • 22
  • 28
  • Hmmm i havent seen any code example like this either, but this definetly works. Thank you, now time for reducing code base like hell :) – Adam Varhegyi Jun 16 '15 at 09:17
1

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

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

    someTextView.setText("Some text");
}
Iliiaz Akhmedov
  • 867
  • 7
  • 17