Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject a ViewStub with ButterKnife?

I want to use a ViewStub with ButterKnife, This is what I've done:

public class ExampleFragment extends Fragment {

    @InjectView ( R.id.stub )
    ViewStub mStub;

    /* A TextView in the ViewStub */
    @InjectView ( R.id.text )
    @Optional
    TextView mText;

    @Override
    public View onCreateView ( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {

        View rootView = inflater.inflate ( R.layout.rootview, container, false );
        ButterKnife.inject ( this, rootView );

        mStub.setLayoutResource ( R.layout.stub_layout );
        View inflated = mStub.inflate ();
        ButterKnife.inject ( mStub, inflated );

        mText.setText("test.");    

        return rootView;
    }
}

and the log says:

mText is a null object reference

I have no idea now, any advice is welcome. Thanks!

like image 408
RockerFlower Avatar asked Dec 26 '14 03:12

RockerFlower


2 Answers

You can create a nested class which holds the views inside the stub.

public class ExampleFragment extends Fragment {

    @InjectView ( R.id.stub )
    ViewStub mStub;

    @Override
    public View onCreateView ( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {

        View rootView = inflater.inflate ( R.layout.rootview, container, false );
        ButterKnife.inject ( this, rootView );

        mStub.setLayoutResource ( R.layout.stub_layout );
        View inflated = mStub.inflate ();
        MyStubView stubView = new MyStubView(inflated); 
        stubView.mText.setText("test.");    

        return rootView;
    }

    // class (inner in this example) that has stuff from your stub
    public class MyStubView {
        @InjectView(R.id.text)
        TextView mText;

        public MyStubView(View view) {
            Butterknife.inject(this, view);
        }
    }
}
like image 169
JChord Avatar answered Sep 23 '22 11:09

JChord


Here is the answer from Jake for this request:

Create a nested class which holds the views inside the stub and then call inject on an instance of that class using the viewstub as the root.

For code refer to this Github issue.

like image 24
CodeFury Avatar answered Sep 25 '22 11:09

CodeFury