Android ButterKnife绑定include布局失败

include布局

<include
    android:id="@+id/tl_reg"
    layout="@layout/layout_toolbar"/>

layout_toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:app="http://schemas.android.com/apk/res-auto">

    <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        app:titleTextColor="@color/secondary_text"
        />
</merge>

情况
1.用findViewById可以找到Toolbar,但是用ButterKnife找不到

2.将include的内容替换掉,用ButterKnife可以找到Toolbar

阅读 9k
3 个回答

给Toolbar填上id试试

这个情况并不需要 merge 吧, 直接将 Toolbar 作为 layout_toolbar.xml 的根元素

其实从原理出发你就会很容易明白,你要绑定的是include中的控件,而不是include,所以自然要为其中的控件定义标识id,要不然无法识别要绑定的对象。并且ButterKnife的本质就是使用了findViewById,如果手动通过findViewById方法也是先获取到include对象,再从中findViewById要绑定的控件。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题