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!
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);
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With