How to inject a ViewStub with ButterKnife?
Asked Answered
D

2

5

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!

Daedal answered 26/12, 2014 at 3:50 Comment(3)
Try View inflated = mStub.inflate (); ButterKnife.inject (this, inflated );Basinger
@NikolaDespotoski I've tried, and this injection replaced the first injection ButterKnife.inject ( this, rootView );, so mStub becomes null. Now I use TextView mText = ( TextView ) inflated.findViewById ( R.id.text ); instead :( Thanks anyway!Daedal
@RockerFlower, why you need the ViewStub object after load its layout, anyway?Goldofpleasure
T
4

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.

Torchwood answered 10/12, 2015 at 4:20 Comment(0)
S
7

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);
        }
    }
}
Subtract answered 4/8, 2015 at 6:35 Comment(0)
T
4

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.

Torchwood answered 10/12, 2015 at 4:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.