How to introduce ViewStub with ButterKnife?

I want to use ViewStub with ButterKnife, here is what I did:

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 magazine says:

mText is a null object reference

I have no idea, any advice is welcome. Thank you

+4
source share
2 answers

Here is the answer from Jake to this request:

Create a nested class that contains the views inside the stub, and then invokes an injection on an instance of this class, using the viewstub as the root.

For code, check out this Github question .

+3
source

You can create a nested class that contains 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);
        }
    }
}
+6
source

Source: https://habr.com/ru/post/1569016/


All Articles