android - Butterknife在自定义视图中绑定到片段

Ofe*_*mon 5 android android-fragments android-view butterknife

我有一个包含自定义视图的片段.

在片段中我这样做ButterKnife.bind:

    View root = inflater.inflate(R.layout.fragment_home, container, false);
    ButterKnife.bind(this, root);
Run Code Online (Sandbox Code Playgroud)

我设法绑定观点.

现在,片段包含我创建的自定义视图.在MenuToggleButton自定义视图中,我想绑定另一个视图,并使用它进行操作.

我遇到的问题是,我不知道如何从自定义视图(位于片段中)内部访问片段的根视图.

public MenuToggleButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        final Activity activity = (Activity) context;
        ButterKnife.bind(this, // need to get the fragment root view somehow);
    }
Run Code Online (Sandbox Code Playgroud)

我怎样才能获得片段根视图以便像我在片段中那样绑定它?

小智 0

您必须在自定义视图中使用 ViewHolder 才能在那里使用 ButterKnife。或者您可以通过 findViewById 传统方式获取视图。因此,使用 ButterKnife,您的自定义视图将如下所示:

class MenuToggleButton{
    public MenuToggleButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        View v = inflate(context, R.layout.menu_toggle_button, this);
        (new ViewHolder(v)).init();
    }
    class ViewHolder{
        @BindView(R.id.some_view)
        SomeView someView;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }

        init() {
            someView.doSomething();
        }

    }
Run Code Online (Sandbox Code Playgroud)

}