【问题标题】:android - Butterknife bind inside custom view to fragmentandroid - Butterknife 在自定义视图中绑定到片段
【发布时间】:2016-09-18 16:00:51
【问题描述】:

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

在片段中,我像这样执行ButterKnife.bind

    View root = inflater.inflate(R.layout.fragment_home, container, false);
    ButterKnife.bind(this, root);

我设法绑定视图。

现在,片段包含我创建的自定义视图。 在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);
    }

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

【问题讨论】:

  • This 可以帮到你。

标签: android android-fragments android-view butterknife


【解决方案1】:

您必须在自定义视图中使用 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();
        }

    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 2016-12-13
    • 2018-03-10
    • 1970-01-01
    相关资源
    最近更新 更多