如何使用ButterKnife注入ViewStub?

时间:2014-12-26 03:50:44

标签: android inject butterknife viewstub

我想在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

我现在不知道,欢迎任何建议。谢谢!

2 个答案:

答案 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)

以下是Jake对此请求的回答:

  

创建一个嵌套类,该类保存存根中的视图,然后使用viewstub作为根在该类的实例上调用inject。

有关代码,请参阅此Github问题。