我想在ButterKnife上使用ViewStub,这就是我所做的:
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;
}
}
并且日志说:
mText is a null object reference
我现在不知道,欢迎任何建议。谢谢!
答案 0 :(得分:6)
您可以创建一个嵌套类来保存存根中的视图。
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);
}
}
}
答案 1 :(得分:4)